vuex
前言
vuex是vue中集中式的状态管理模式,存储整个系统的状态。
一、store是什么?
vuex的实现通过store来解决,我们可以通过操作store来修改里面state对应的数据。
在Vuex中,store由以下几个核心概念组成:
State(状态):存储应用程序的状态数据,通常是一个JavaScript对象。
Mutations(变更):定义了修改状态的方法,通过提交(commit)一个mutation来改变状态。Mutations是同步操作,用于确保状态的可追踪性和可维护性。
Actions(动作):用于处理异步操作和复杂的业务逻辑。Actions提交(mutating)一个或多个mutation来改变状态,可以包含任意异步操作。
Getters(获取器):类似于组件中的计算属性,允许从store中派生出一些状态,以供组件使用。
其中还有module是,为模块,用于解决数据冗余问题。
二、使用步骤
1.安装vuex
代码如下(示例):
npm install vuex
2.编写基本数据(index.js)
代码如下(示例):
// main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount(state) {
return state.count * 2
}
}
})
new Vue({
store,
// ...其他配置
}).$mount('#app')
上面是一个js文件,一般index.js文件存储的都是整个项目的状态,即全局。在任何一个组件里都可以通过类似以下方法调用:
methods:{
increment(){
this.$store.commit('increment')
},
incrementByN(){
this.$store.commit('incrementByN',10)
},
incrementByP(){
this.$store.commit('incrementByP',{
count:2
})
},
incrementByDis(){
this.$store.dispatch('increment')//触发的是actions里的函数
},
incrementAsync(){
this.$store.dispatch('incrementAsync')//触发的是actions里的函数
}
}
以上内容主要涉及如何在组件的函数中调用store里的属性和函数。
3.modules(XXX.js)
模块化操作,即一个组件对应一个store,或者多个组件对应一个store,然后将这个store注册到根store中。模块化一定要注意命名空间,namespaced:true。
modules: {//模块化
storeA:ComponentA,
storeC:ComponentC
}
引入文件为:
import ComponentA from '../store/componentA'
import ComponentC from '../store/componentC'
引入的都为js文件,每一个js文件其实都是一个store。
例如上面的componentA.js文件:
export default {
namespaced:true,
state: {
countA: 0
},
mutations: {
increment(state) {
state.countA++
}
},
actions: {
increment(context) {
if (context.rootState.countS==0){
context.commit('increment')
}
}
},
getters: {
doubleCountA(state) {
return state.countA * 2
}
}
}
那么在组件中如何访问?
computed:{
getCountA(){
// return this.$store.getters['storeA/doubleCountA']
return this.$store.state.storeA.countA;
}
},
methods:{
increment() {
this.$store.commit('storeA/increment'); // 调用storeA模块中的increment mutation
},
incrementAsync() {
this.$store.dispatch('storeA/increment'); // 调用storeA模块中的increment action
}
}
除此之外,还可以通过map来进行映射:
computed:{
...mapState('storeC',['countC']),
...mapGetters('storeC',['getCountC'])
},
methods:{
// ...mapMutations('storeC',['increment']),
// ...mapActions('storeC',['increment'])
...mapMutations('storeC',{
incrementMumation:'increment'
}),
...mapActions('storeC',{
incrementAction:'increment'
})
}
组件里调用:
<p>countC is:{{countC}}</p>
<p>countC * 3 is:{{getCountC}}</p>
<button @click="incrementAction">(actions)点击加1</button>