VueX 替换状态中的数组数据
VueX replace array data in state
我不确定如何解释这个所以让我们试一试。只知道我只是在学习 VueX 的潜力,所以请多多包涵。
我有一个名为 currentRoom
的状态对象数组,它一次只能保存一个对象。所以顾名思义,这意味着用户在房间内,然后他们改变房间,因此 currentRoom 应该将其数据更改为新房间。现在,它所做的一切都是给自己添加越来越大的对象。
我需要改变什么来实现我的目标?
export const actions = {
[types.CURRENT_ROOM]({state, commit}, room) {
commit(types.CURRENT_ROOM, {room});
},
}
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom.push(room)
},
}
export const types = {
CURRENT_ROOM: 'current_room'
}
我在 VUE 文件中使用的代码
this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);
在我的脑海里,我觉得应该有类似 REPLACE 而不是 dispatch 的东西,或者也许我只是在想这个错误。所以教育和教育我哦,Stack Overflow 的伟大人物!
旁注:Vue 3 和 VueX 4
数组增长是因为您正在调用 Array.prototype.push()
,它会向数组追加一个项目。假设是单元素数组,可以用方括号替换数组元素,数组索引为0
:
// store.js
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom[0] = room
},
}
但是,数组旨在保存多个值。如果只有一个值,则不需要数组。
state.currentRoom
应从 Array
更改为 Object
:
// store.js
export const state = () => ({
currentRoom: {} // or null
})
并且突变应该将新值分配给 state.currentRoom
:
// store.js
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom = room
},
}
我不确定如何解释这个所以让我们试一试。只知道我只是在学习 VueX 的潜力,所以请多多包涵。
我有一个名为 currentRoom
的状态对象数组,它一次只能保存一个对象。所以顾名思义,这意味着用户在房间内,然后他们改变房间,因此 currentRoom 应该将其数据更改为新房间。现在,它所做的一切都是给自己添加越来越大的对象。
我需要改变什么来实现我的目标?
export const actions = {
[types.CURRENT_ROOM]({state, commit}, room) {
commit(types.CURRENT_ROOM, {room});
},
}
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom.push(room)
},
}
export const types = {
CURRENT_ROOM: 'current_room'
}
我在 VUE 文件中使用的代码
this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);
在我的脑海里,我觉得应该有类似 REPLACE 而不是 dispatch 的东西,或者也许我只是在想这个错误。所以教育和教育我哦,Stack Overflow 的伟大人物!
旁注:Vue 3 和 VueX 4
数组增长是因为您正在调用 Array.prototype.push()
,它会向数组追加一个项目。假设是单元素数组,可以用方括号替换数组元素,数组索引为0
:
// store.js
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom[0] = room
},
}
但是,数组旨在保存多个值。如果只有一个值,则不需要数组。
state.currentRoom
应从 Array
更改为 Object
:
// store.js
export const state = () => ({
currentRoom: {} // or null
})
并且突变应该将新值分配给 state.currentRoom
:
// store.js
export const mutations = {
[types.CURRENT_ROOM](state, {room}) {
state.currentRoom = room
},
}