![](/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.