![](/img/trans.png)
[英]Using bracket notation with a variable to access object property returns undefined
[英]Why can't I assign a property to an object using bracket notation + a variable?
我对Vuex很新,并试图为Vuex状态赋值(( state.map.status.isReady
)。
但是,我想让我的代码可以重用,所以我创建了一个函数changeMapStatus(state, key, value)
来实现它。
此函数将属性state.map.status.key
修改为接收的value
。
但是,当我从组件文件调用this.$store.commit('changeMapStatus', 'isReady', true)
,它只是删除state.map.status.isReady
并且该属性变为undefined
。
另一方面,如果我将功能更改为
changeMapStatus(state, value) {
state.map.status.isReady = value;
}
它以某种方式工作。
你能帮助我,哪一点我弄错了?
非常感谢!
store.js (Vuex)
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { map: { status: { isReady: false, }, }, }, mutations: { changeMapStatus(state, key, value) { state.map.status[key] = value; } }, });
您可以将对象作为包含key
和value
参数传递,如下所示:
changeMapStatus(state, myObj) {
state.map.status[myObj.key] = myObj.value;
}
并称之为:
this.$store.commit('changeMapStatus', {key:'isReady', value:true})
根据Vuex
官方文档 ,变异需要2个参数状态和有效负载。 您可以使用spread运算符从有效负载中获取值。
changeMapStatus(state, {key, value}) {
state.map.status[key] = value;
}
this.$store.commit('changeMapStatus', {key: 'isReady', value: true})
或者你可以像这样使用它
changeMapStatus(state, payload) {
state.map.status = {
...state.map.status,
...payload,
}
}
this.$store.commit('changeMapStatus', { isReady: true });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.