vuex的五个属性及使用方法示
时间: 2023-06-20 19:03:54 浏览: 70
Vuex是Vue.js的官方状态管理库,它包含了五个核心属性,分别是:
1. state:Vuex中的state就相当于Vue中的data,用于存储数据状态,可以通过`this.$store.state`来访问。state的使用方法如下:
```
// 在store中定义state
const store = new Vuex.Store({
state: {
count: 0
}
})
// 在组件中访问state
computed: {
count() {
return this.$store.state.count
}
}
```
2. getters:Vuex中的getters相当于Vue中的computed,用于派生出一些新的状态,并且会对state进行缓存,只有当依赖的state发生变化时,才会重新计算。getters的使用方法如下:
```
// 在store中定义getters
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
doubleCount(state) {
return state.count * 2
}
}
})
// 在组件中访问getters
computed: {
doubleCount() {
return this.$store.getters.doubleCount
}
}
```
3. mutations:Vuex中的mutations用于修改state中的数据状态,只能进行同步操作,且不支持异步操作。mutations的使用方法如下:
```
// 在store中定义mutations
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// 在组件中调用mutations
methods: {
increment() {
this.$store.commit('increment')
}
}
```
4. actions:Vuex中的actions用于处理异步操作以及多个mutations的组合操作,它可以进行异步操作,并且通过commit方法来触发mutations的同步操作。actions的使用方法如下:
```
// 在store中定义actions
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
// 在组件中调用actions
methods: {
incrementAsync() {
this.$store.dispatch('incrementAsync')
}
}
```
5. modules:Vuex中的modules用于将store分割成多个模块,每个模块都有自己的state、getters、mutations和actions。modules的使用方法如下:
```
// 在store中定义modules
const store = new Vuex.Store({
modules: {
moduleA: {
state: {},
getters: {},
mutations: {},
actions: {}
},
moduleB: {
state: {},
getters: {},
mutations: {},
actions: {}
}
}
})
// 在组件中访问moduleA的state
computed: {
count() {
return this.$store.state.moduleA.count
}
}
```