【问题标题】:V-model is updating unreferenced state dataV-model 正在更新未引用的状态数据
【发布时间】:2021-11-25 21:46:08
【问题描述】:

我正在尝试将 vuex 存储中的对象复制到本地组件对象,以便我可以在本地更改它而不修改存储状态对象。但是,当我将本地对象与 textarea v-model 关联时,它会更改存储状态数据,即使它没有被直接引用。我不确定这是怎么发生的,甚至是可能的。

<v-textarea v-model="currentObj.poltxt" solo light></v-textarea>

  watch: { //watch for current UID changes
    "$store.state.currentUID"(nv) {
      //Clearing the local temporary object
      this.currentObj = {};
      //Moving the store state data into the local object
      this.currentObj = this.$store.state.docuMaster[this.$store.state.currentUID];
    }
  }

watch 函数正在执行,当我控制台日志 this.$store.state.docuMaster[this.$store.state.currentUID] 我可以看到 v-model 甚至直接更新它尽管它引用了 currentObj。知道为什么会这样吗?文本框未在代码中的任何其他位置引用商店。

【问题讨论】:

  • this.$store.state.docuMaster[this.$store.state.currentUID] 对象还是嵌套对象?
  • docuMaster 本身就是一个嵌套对象。
  • 没错,docuMaster 中的 currentId 条目又是一个嵌套对象。无论如何,请在下面查看我的解决方案

标签: vue.js vuetify.js vuex


【解决方案1】:

如果this.$store.state.docuMaster[this.$store.state.currentUID] 不是嵌套对象,请尝试使用

//Moving the store state data into the local object
      this.currentObj = Object.assign({}, this.$store.state.docuMaster[this.$store.state.currentUID]);

如果this.$store.state.docuMaster[this.$store.state.currentUID]) 是嵌套对象,那么你必须进行深度克隆

this.currentObj = JSON.parse(JSON.stringify(this.$store.state.docuMaster[this.$store.state.currentUID]));

注意: 我的意思是嵌套对象

docuMaster: {
 UID: {
  ...
   xyz: {}
 },
....
}

不是嵌套的 obj 意味着

docuMaster: {
 UID: {
  //no inner objects
 },
....
}

【讨论】:

  • Object.assign 似乎正在工作。谢谢!知道为什么会这样吗?为什么 v-model 从不引用它时会影响 docuMaster?
  • 太棒了!如果这有帮助,请考虑给予支持并接受答案
  • 这是因为当你直接分配它时,它会被引用复制。因此,即使它存储在不同的变量中,它仍然共享相同的引用,因此在一个地方更改时会反映另一个地方
  • 其实我说得太早了。它可以复制它,但现在 v-model 无法更改 currentObj。对象保持静态,文本区域不会改变它。
  • 是的,因为如果你在 v-model 中使用它,更新应该只通过 v-model 发生,但在我们的例子中,更新可能通过 v-model 或通过 watch 两种方式发生,因此有冲突
猜你喜欢
  • 2016-11-12
  • 2022-08-18
  • 2018-10-02
  • 2021-04-10
  • 1970-01-01
  • 2019-10-26
  • 2018-12-30
  • 2015-10-15
相关资源
最近更新 更多