[Vuejs]-Variable Doesn't Change in Vue.js

0👍

I think it’s because of asynchronous request

It definitely is.

If you’re not familiar with writing asynchronous code, I would read up on that first (in particular promises).

console.log(qty) returns 0 because that code is executed immediately after the request is sent and before the response has come back from the server. The callback function you passed to then is the function that will be executed once the response has come back from the server, and only then will you be able to obtain qty from the response data.

If you want to return qty from that function (which is what it looks like you are trying to do), then that function must return a promise that once resolved will contain the qty value (code isn’t blocked in JavaScript, hence the reason for the promise).

getQuantity() {
  return (qtyId) => {
    return axios.get(window.location.origin + '/api/quantity/' + qtyId)
    .then(res => {
      return res.data.qty;
    });
  }
},

Why is it a computed property instead of a method? I think a different approach would be better, but I don’t know exactly how this code fits into your project.

Leave a comment