【问题标题】:Why is the vuex component isn't updated, despite the state updating?尽管状态更新,为什么 vuex 组件没有更新?
【发布时间】:2016-12-13 07:23:59
【问题描述】:

当我加载我的页面时,我会获取optboxes items 的列表。

来源

项目来源已上线:

optboxes 页面

HTTP 请求很好地发送并返回足够的数据:

created(){
    this.getOptboxes();
},
components: {
    'optbox': OptboxComponent,
},
methods: {
    getOptboxes() {
        optboxes.all().then((response) => {
            this.setOptboxes(response.data.output);
    }).catch(() = > {
            this.no_optbox_message = 'there is no optbox';
        logging.error(this.$t('optboxes.get.failed'))
    });
    }
},
vuex: {
    actions: { setOptboxes: actions.setOptboxes},
    getters: { optboxesList: getters.retrieveOptboxes}
}

我正在迭代结果如下:

<div v-for="optbox in optboxesList" class="panel panel-default">
     <optbox :optbox="optbox"></optbox>
</div>

商店

const state = {
    optboxes: {
        /*
        'akema': {
            hostname: "192.168.2.23",
            id: "akema",
            printers: [
                {
                    description: "bureau",
                    destination_port: 9100,
                    forward: "normal",
                    hostname: "1.2.3.4",
                    id: 0,
                    listening_port: 9102
                }
            ]
        }
        */
    }
};

问题

如果我切换到其他页面并返回,则会出现列表。我还注意到,使用 Vuex 扩展,我可以提交状态并查看更改。

为什么我的更改没有自动应用?

【问题讨论】:

    标签: components vue.js vuex


    【解决方案1】:

    由于Change Detection Caveats,我不得不更改我的数据结构。

    由于 JavaScript 的限制,Vue.js 无法检测到以下内容 更改为数组:

    • 当您直接使用索引设置项目时,例如vm.items[0] = {};
    • 当您修改 Array 的长度时,例如vm.items.length = 0

    商店

    optboxes 现在是一个数组。

    const state = {
        optboxes:[]
    }
    

    然后相应地更新我的突变以编辑数组。

    【讨论】:

      【解决方案2】:

      也许这是反应性问题?!我假设你的 setOptboxes 突变没有被 vue 拾取:

      setOptboxes(state, optboxes) {
          for (var optbox of optboxes) {
              state.optboxes[optbox.id] = optbox;
          }
      }
      

      你可以在这里阅读:

      https://vuejs.org/guide/list.html#Caveats

      https://vuejs.org/guide/reactivity.html

      文档解决方案是使用:

      state.optboxes.$set(optbox.id, optbox);
      

      这将触发视图更新。

      【讨论】:

      • 不确定是否相关,但state.optboxes 不是Array,而是Object。使用$set() 方法失败了我的承诺
      【解决方案3】:

      使用Vue.set 为我编辑它。看看here

      【讨论】:

        猜你喜欢
        • 2021-10-05
        • 2021-08-04
        • 2019-03-20
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 2019-12-12
        • 2021-06-07
        • 2020-11-23
        相关资源
        最近更新 更多