计算属性不响应状态变化



我正在制作一个产品概述页面,该页面根据您正在查看的当前类别发出api调用:

store.dispatch("tweakwise/fetchAPIAttributesLayeredNavigation", {
tweakwiseCategory,
this.pageNumber,
}

在我的Store中,来自此api调用的数据将在以下VueX Store状态中设置:

this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes: []

我想在我的前端对这个数据做出反应,但是我的Computed方法似乎没有对这个变化做出反应。正如你在下面的函数中看到的那样,我添加了一个Catch来防止出现"非定义"。错误。然而,在状态设置之后,将不会调用该函数。此计算属性也被添加到组件

的Mount()操作中。
computed: {
initialFetchProducts() {
this.fetchProducts(
this.$store.state.tweakwise?.tweakwiseLayeredNavigationAttributes || []
);
},
},

为你想要观察的状态设置计算属性,然后为这个道具创建watch()。在watch中,你可以对计算属性的改变做出反应。

<template>
<div v-for="product in products"></div>
</template>
<script>
export default {
data: {
return {
products: [],
}
},
computed: {
tweakwiseLayeredNavigationAttributes() {
return this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes;
},
},
watch: {
// on every tweakwiseLayeredNavigationAttributes change we call fetchProducts
tweakwiseLayeredNavigationAttributes: {
handler(newValue, oldValue) {
this.fetchProducts(newValue);
},
deep: true, // necessary for watching Arrays, Object
immediate: true, // will be fired like inside mounted()
}
},
methods: {
async fetchProducts(params) {
const products = await axios.get('/api', params);
this.products = products;
}
}
};
</script>

最新更新