Answer the question
In order to leave comments, you need to log in
How to change data property of VUE from application method with data received from server?
Online store website, backend on Laravel, shopping cart on VUE.JS.
When the shopping cart page is opened, the data in JSON format is assigned to the data property of the items and the shopping cart page opens and runs successfully.
To change the number of goods, remove from the goods from the cart, the getUpdate method was created, which on AJAX receives updated data from the server - a new object with data that must be passed to the data property of the items, in order to reactively change the page without reloading.
const app = Vue.createApp({
data() {
return {
items: {!! json_encode($data) !!}, // данные, при загрузке страницы
}
},
methods: {
getUpdate: function (id, qty, type) {
let formData = new FormData();
formData.append('id', id);
formData.append('qty', qty);
formData.append('type', type);
const cart = new XMLHttpRequest();
cart.open('POST', '/cart-update', true);
cart.setRequestHeader('X-CSRF-Token', '{{csrf_token()}}');
cart.send(formData);
cart.onload = function() {
if (cart.status != 200) {
console.log(`Ошибка ${cart.status}: ${cart.statusText}`);
} else {
this.items = JSON.parse(cart.response); // Ответ сервера, новые данные полученные с сервера, THIS - не принадлежит приложению VUE, указывает на функцию
console.log(JSON.parse(cart.responseText));
}
}
}
},
Answer the question
In order to leave comments, you need to log in
The construction this.items = JSON.parse(cart.response); - doesn't work because ajax function in getUpdate method has its own context
Reaching app.items also fails.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question