2017-07-21 56 views
0

我无法在我的计算属性中更改变量qtyVue.js中的变量不会更改

getQuantity(){ 

       return (qtyId) => { 

        var qty = 0; 
        axios.get(window.location.origin + '/api/quantity/' + qtyId) 
        .then(res => { 
         console.log(res.data.qty) 
         qty = res.data.qty 
        }) 
        .catch() 

        console.log(qty) 
        return qty 

       } 
      }, 

这是一个使用axios的异步请求。 console.log(res.data.qty)工作正常,它输出4,但console.log(qty)0。我认为这是因为异步请求...我如何使它工作... TY

回答

0

我也有这个问题了很多。有一个解决方法。 尝试添加数量到“数据”在vuejs,所以它成为反应,也有另一件事与匿名方法,所以也许尝试。

data() { 
    return { 
    qty: 0 
    } 
}, 
methods: { 
getQuantity(){ 

    const self = this; 

      return (qtyId) => { 
       axios.get(window.location.origin + '/api/quantity/' + qtyId) 
       .then(res => { 
        console.log(res.data.qty) 
        self.qty = res.data.qty 
       }) 
       .catch() 

       console.log(self.qty); 
       return self.qty; 

      } 
     }, 
+0

它不断循环和改变数量。 – Rbex

+0

哦,没有看到它是一个循环,是确保您的数据准时到达,有时需要使用超时。另一件事是知道在某种特定方法中输出的“这个”。我会推荐chrome vuejs插件。并且不要将请求放在循环中,首先在集合中捕获所有数据,然后使用它。 –

0

我想这是因为异步请求

这肯定是的。

如果您不熟悉编写异步代码,我会先阅读(特别是承诺)。

console.log(qty)返回0,因为该代码在发送请求之后并且响应从服务器返回之前立即执行。您传递给then的回调函数是一旦响应从服务器返回时将执行的函数,只有这样您才能从响应数据中获得qty

如果你想从该函数返回qty(这是它看起来像你正在尝试做的),那么该函数必须返回,一旦解决了将包含qty值(代码不被阻挡在JavaScript中的承诺,因此承诺的原因)。

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

为什么它是一个计算属性而不是方法?我认为一种不同的方法会更好,但我不确切知道这些代码如何适合您的项目。

+0

我环在这里是代码'TR V-用于= “(productableMerchant,指数)product.productable_merchants”> \t \t \t \t​​{{productableMerchant.name}} \t \t \t \t​​品牌 \t \t \t \t​​{{productableMerchant.pivot.price}} \t \t \t \t​​{{getQuantity(productableMerchant.pivot。quantity_id)}} \t \t \t \t​​{{productableMerchantDisc(指数)}} \t \t \t \t​​{{productableMerchant.pivot.created_at}} \t \t \t \t​​' – Rbex

+0

而这一次... '​​{{getQuantity(productableMerchant.pivot.quantity_id)}}' – Rbex

+0

不,它不起作用它只显示'{}'。 – Rbex