计算属性不会对状态变化做出反应

Computed properties are not reacting to state change

我正在开发产品概览页面,该页面会根据您正在查看的当前类别发出 API 呼叫:

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

在我的商店中,来自此 API 调用的数据将设置为以下 VueX 商店状态:

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

我想在我的前端对这些数据做出反应,但我的计算方法似乎没有对这个变化做出反应。您还可以在下面的函数中看到,我添加了一个 Catch 来防止出现“未定义”错误。但是,在设置状态后将不会调用该函数。 这个计算的 属性 也被添加到组件

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

为您要观看的状态进行计算 属性, 而不是为此道具创建 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>