【问题标题】:"VueX do not mutate vuex store state outside mutation handlers" for dynamic properties. How to unbind?动态属性的“VueX 不会在突变处理程序之外改变 vuex 存储状态”。如何解绑?
【发布时间】:2020-10-18 23:18:07
【问题描述】:

我正在使用 Vue 构建一种带有动态元元素的表单构建器。见这里:

<div v-for="item in getFieldType(selectedElement.type).meta"
     :key="item.id">
  <div class="form-group">
    <label>{{ item.label }}</label>
    <TextField
      :value="selectedElement.meta[item.id]"
      :label="item.label"
      :name="item.label"
      type="text"/>
  </div>
</div>

这只是简单地介绍了字段类型的定义+从 API 中加载字段:

mounted()
  {
    this.file = await this.$store.dispatch('files/fetch', this.$route.params.id);
    // [...]
    this.selectedElement = this.file.fields[1].rawFields; // Simplified
  },

  data() {
    return {
      fieldTypes: [
        {
          type: 'singleline-text',
          label: 'Singleline Textfields',
          config: {
            minwidth: 50,
            name: true,
          },
          meta: [
            {
              type: 'text',
              label: 'Prefilled Value',
              hint: 'This value will be prefilled',
              id: 'prefilled'
            }
          ]
        }
      ]
    };
  }

所以基本上这是从 VueX 使用的:this.file.fields[1].rawFields

不幸的是,当我尝试编辑 TextField 时,出现以下错误:

[vuex] do not mutate vuex store state outside mutation handlers.

我在文档中研究并发现了这一点:https://vuex.vuejs.org/guide/forms.html,但这并没有帮助,因为我的方法更加动态。我必须找到一种方法将 rawFields 从 vueX 状态“解除绑定”,因为我以后不再需要它了。我不想将严格设置为假。有什么优雅的方法可以解决这个问题吗?

我还发现了这篇文章,它描述了如何将其保持在 Vue 状态:Vuex - Do not mutate vuex store state outside mutation handlers

但在我的情况下,解除绑定而不是编写更多的 getter、setter、模糊/焦点侦听器等会更有意义。

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    您可以尝试添加lodash并使用此功能https://lodash.com/docs/4.17.15#cloneDeep

    在挂载时这样做

    this.selectedElement = _.cloneDeep(this.file.fields[1].rawFields); // Simplified
    

    【讨论】:

    • 是的,谢谢。使用npm i --save lodash.clonedeep 导入并添加import lodash from 'lodash';
    • 再提示:这将返回一个对象,即使它之前是一个数组。这有助于将其恢复为数组:stackoverflow.com/questions/38824349/…
    猜你喜欢
    • 2019-11-30
    • 2019-09-24
    • 2018-02-13
    • 2022-01-09
    • 2020-10-31
    • 1970-01-01
    • 2020-03-30
    • 2023-03-09
    • 2016-11-16
    相关资源
    最近更新 更多