[英]How to Add State Properties dynamically via Mutations
I want to add Properties into store.state
via mutations. 我想通过突变将属性添加到
store.state
。 Very Simple Example: 非常简单的例子:
// state.js
export default () => ({
Prop1: '1',
Prop2: '2'
})
//mutations.js
export default {
makeProp (state, anotherProp) {
return state.anotherProp = anotherProp;
}
}
// State Client
export default () => ({
Prop1: '1',
Prop2: '2',
anotherProp: 'what ever'
})
It all works well. 一切都很好。 But the nasty thing is, it seems not to be reactive in Vue-Component anymore.
但是令人讨厌的是,在Vue-Component中似乎不再具有反应性。 If
anotherProp
gets a new value, the component doesnt render it. 如果
anotherProp
获取新值,则组件不会渲染它。
If i have defined anotherProp
fixed in State, it is reactive. 如果我定义
anotherProp
固定在State中的anotherProp
,则它是反应性的。 I can imagine why. 我可以想象为什么。 I guees the reactivity of Vue needs to know its data, so it knows on which changes to listen to.
我猜测Vue的反应性需要知道其数据,因此它知道要听哪些更改。
But what can I do? 但是我能做什么呢? I really need to add states via mutation.
我真的需要通过突变添加状态。 The background is:
背景是:
We have a Databasemanagement implemented. 我们实现了数据库管理。 So if a user creates a new database, the vuex store needs to know these dynamically.
因此,如果用户创建新数据库,则vuex存储需要动态地知道这些。 So for now, we have a mutation, which creates states for each database.
所以现在,我们有了一个突变,它为每个数据库创建状态。
Can I have any way around that? 请问有什么办法吗? I still have no idea :D
我还是不知道:D
As said by Lewis and According to vuex mutations rules seems all upfront fiends should exists when the store initializes. 就像Lewis和根据vuex突变所说的那样,商店初始化时似乎应该存在所有前期恶魔。
A simple solution could be to initialize an upfront property which contains all properties you want. 一个简单的解决方案是初始化一个包含您想要的所有属性的前期属性。 For example:
例如:
export default () => ({
data: {
Prop1: '1',
Prop2: '2'
}
})
Doing this you could use: 为此,您可以使用:
Vue.set(data, 'anotherProp', 'what ever')
or 要么
state.data = { ...state.data, 'anotherProp': 'what ever' }
Here is the mutation to create the State Property and I try to integrate making this Prop reactive for Vue 这是创建State Property的突变,我尝试整合以使该Prop对Vue具有反应性
UPDATE -------------------------------------------- 更新--------------------------------------------
// mutation.js
import Vue from 'vue'
export default {
stateUpdate (state, target) {
Vue.set(state, target.t, target.data);
},
}
This is what I needed, because I needed it mutate
and set
in Vuex Store itself, not via component. 这就是我需要的,因为我需要对它进行
mutate
并在Vuex Store本身中进行set
,而不是通过组件。
Thx for your help :) 感谢您的帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.