vuex保存对象或者数组
时间: 2023-10-02 17:13:28 浏览: 64
在Vuex中,可以使用state来保存对象或数组。
1. 保存对象
在Vuex的state中,可以定义一个对象类型的属性,例如:
```
state: {
user: {
name: 'John',
age: 30
}
}
```
在组件中可以通过以下方式访问和修改user对象的属性:
```
this.$store.state.user.name // 访问user的name属性
this.$store.state.user.age = 31 // 修改user的age属性
```
2. 保存数组
同样地,在Vuex的state中,可以定义一个数组类型的属性,例如:
```
state: {
todos: [
{ id: 1, text: 'Buy milk', done: false },
{ id: 2, text: 'Do laundry', done: true }
]
}
```
在组件中可以通过以下方式访问和修改todos数组的元素:
```
this.$store.state.todos[0].text // 访问todos数组的第一个元素的text属性
this.$store.state.todos.push({ id: 3, text: 'Clean room', done: false }) // 向todos数组中添加一个新元素
```
需要注意的是,当我们需要修改state中的对象或数组时,应该使用Vuex的mutation来进行修改,而不是直接修改state。例如:
```
mutations: {
updateUserAge (state, newAge) {
state.user.age = newAge
},
addTodo (state, newTodo) {
state.todos.push(newTodo)
}
}
```
在组件中,可以通过以下方式触发mutation来修改state中的对象或数组:
```
this.$store.commit('updateUserAge', 31) // 修改user的age属性为31
this.$store.commit('addTodo', { id: 3, text: 'Clean room', done: false }) // 向todos数组中添加一个新元素
```