简体   繁体   English

vuex 突变不会更新 DOM

[英]vuex mutation doesn't update DOM

I'm rendering a list based on an object.我正在渲染一个基于 object 的列表。 I'm adding new elements to this object by help of the mutations.我在突变的帮助下向这个 object 添加了新元素。 When I log this.$store.state.myObject to console, I can see that it is updating.当我将 this.$store.state.myObject 记录到控制台时,我可以看到它正在更新。 However, my list is not updated.但是,我的列表没有更新。

Actually, I got lucky and I fixed this issue by adding the line of code below in my mutation.实际上,我很幸运,我通过在我的突变中添加下面的代码行来解决这个问题 (I found out that this can help DOM update.) (我发现这可以帮助 DOM 更新。)

But I'd like to learn if this is a good solution.但我想知道这是否是一个好的解决方案。

state.realms = Object.assign({}, state.realms)

Here is my whole mutation:这是我的整个突变:

addToRealms: (state, val) => {
        var id = val.id
        var realmName = val.name.en_US
        state.realms[id] = { name: realmName }
        state.realms = Object.assign({}, state.realms)
        }

And here is my vue page code这是我的 vue 页面代码

<q-btn flat
  v-for="(realm,code) in realms"
  :key="code"
  @click="selectRealm(realm)"
  :label="realm.name"
  clickable/>

I defined realms as a computed property.我将领域定义为计算属性。

computed: {
realms () {
  return this.$store.state.realms
}

Further info: I use vue.js devtools extension, when I track my commit on vuex store I can see that I'm really changing the state.更多信息:我使用 vue.js devtools 扩展,当我在 vuex 商店跟踪我的提交时,我可以看到我真的在改变 state。 But It doesnt affect immediately.但它不会立即影响。 If I press commit all button, my list gets updated.如果我按下全部提交按钮,我的列表就会更新。

提交 Vue Devtools 上的所有按钮 Thanks.谢谢。

When you use当你使用

state.realms = Object.assign({}, state.realms)

you basically are recreating a new object based on the previous one (breaking the references in case there are not nested objects), and that's the reason why in this way the list get updated.你基本上是在前一个的基础上重新创建一个新的 object (如果没有嵌套对象,则打破引用),这就是为什么以这种方式更新列表的原因。

Give a read to this article to understand more about deep-cloning and breaking references.阅读本文以了解有关深度克隆和破坏引用的更多信息。

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object Object.assign() 方法用于将所有可枚举自身属性的值从一个或多个源对象复制到目标 object

When you add new properties to the object, those are not reactive.当您向 object 添加新属性时,这些属性不会反应。 To make them reactive, use the Vue.set() method, ( docs here ).要使它们具有响应性,请使用 Vue.set() 方法(此处的文档)。

Vue.set(state.realms[id],'name', realmName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM