M
M
Maxim Volkov2021-11-08 10:43:27
Vue.js
Maxim Volkov, 2021-11-08 10:43:27

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));
              }
          }
      }
  },


The data comes from the server, but I don't know how to change the data property items. The construction this.items = JSON.parse(cart.response); - does not work, because the ajax function in the getUpdate method has its own context: this. Reaching app.items also fails.

Please Help, tell me - how to change the data property with data received from the server?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-08
@voland700

The construction this.items = JSON.parse(cart.response); - doesn't work because ajax function in getUpdate method has its own context

I suggest you google ways to save context - this question has been raised hundreds (if not thousands) of times on this resource alone.
Reaching app.items also fails.

The root bean instance returns the mount method, not createApp.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question