【问题标题】:Computed properties are not reacting to state change计算属性对状态变化没有反应
【发布时间】:2021-10-31 21:45:40
【问题描述】:

我正在开发一个产品概览页面,该页面根据您正在查看的当前类别发送 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 || []
      );
    },
},

【问题讨论】:

    标签: vue.js dynamic state vuex store


    【解决方案1】:

    为你想观察的状态创建计算属性, 而不是为这个道具创建 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>
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    • 然后像这样使用观察者:
        ?或者您将如何实施?
    • 这也是您在自己的项目中使用这种反应式流程的方式吗?
    • 我不知道你的具体情况,但是是的,当我想重新渲染列表时,我正在做类似的事情,这取决于一些道具
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2019-08-18
    • 2018-06-13
    • 2020-03-02
    • 2021-04-17
    • 1970-01-01
    • 2022-06-21
    相关资源
    最近更新 更多