【问题标题】:Store value changes but doesn't affect computed property in component存储值更改但不影响组件中的计算属性
【发布时间】:2019-05-28 23:02:58
【问题描述】:

我正在使用 VueJS 构建一个树形视图,我想将最后点击的项目保存在商店中,然后使用此商店显示组件中最后点击的项目。

我在要显示项目的组件中使用计算属性。问题是,当 store 发生变化时,它不会影响组件中的计算属性。

相关代码见此链接: https://jsfiddle.net/eywraw8t/527884/

Vue.component('category-list', {
    template: `
    <div>
  <b>{{selectedCat}}</b>
  <ul>
        <category v-for='(catg, catgIdx) in categories' :category='catg' :key='catgIdx'
                            v-on:category-selected='categorySelected'/>
    </ul>
  </div>
  `,
    props: {
        categories: { type: Array, default: () => [] }
    },
  computed:{
  selectedCat(){
    return bookmarksStore.state.selectedCategory
  }
}
})

【问题讨论】:

    标签: vue.js vue-reactivity


    【解决方案1】:

    您不依赖 computed 上的响应式数据 (data,props)。因此,当bookmarksStore 更改时,不会触发您的计算属性。

    我建议在您的情况下使用 Vuex 来创建您的商店。

    使用 Vuex

    import Vue from "vue";
    import Vuex from "vuex";
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
        state:{
          selectedCategory: {name: ""}
      },
      getters: {
        getselectedCategory: state => {
            return state.selectedCategory;
        }
      },
      mutations:{
        selectCategory(state, payload) {
            state.selectedCategory.name = payload
        }
      }
    })
    
    new Vue({
      el: "#app",
      store,
      data: {
    ...
    

    然后,您可以使用this.$store.commit('selectCategory', category) 更新您的商店的selectedCategory,您的计算属性将如下所示

    computed:{
      selectedCat(){
        return this.$store.getters.getselectedCategory
      }
    }
    

    没有 Vuex

    如果您不想使用 Vuex,请在您的 Vue 根实例数据中传递您的 bookmarksStore

    new Vue({
      el: "#app",
      data: {
        bookmarksStore: new BookmarksStore(),
        ...
    

    您现在可以使用 propsbookmarksStore 传递给子组件,并使用传递给 Vue 根实例的事件对其进行更新。这样,bookmarksStore 是每个子组件中的propscomputed 属性将被触发。

    【讨论】:

    • 不使用vuex可以解决这个问题吗?如果是,我该怎么做?
    • 我刚刚更新了我的答案以解决您在没有 Vuex 的情况下遇到的问题。尽管我强烈建议在您的情况下使用 Vuex。
    • 最佳答案。谢谢!
    猜你喜欢
    • 2017-04-16
    • 2020-11-12
    • 2020-11-24
    • 2010-12-24
    • 2021-10-31
    • 2015-04-18
    • 2020-01-27
    • 2021-12-16
    • 2019-11-07
    相关资源
    最近更新 更多