Vuex是Vue的状态管理工具,通过Vuex可以让Vue页面中所有的页面获取到公共的数据。
核心属性及使用方法
1、state:存放数据的地方,类似于vue中的data
(1)直接获取
<p>获取count --{ { $store.state.count }}</p>
(2)通过mapState获取,此方法需要在computed中调用
//导入mapState
import { mapState } from "vuex";<p>mapState获取count--{ { count }}</p>
computed:{
...mapState(["count"])
}
2、getters:从基本数据(state)派生的数据,相当于state的计算属性,此方法调用同样有两种方法
(1)直接获取
<p>直接使用--{ { $store.getters.count }}</p>
(2)通过mapGetters获取,同样在computed中调用
<p>mapGetters获取--{ { count }}</p>
computed:{
...mapGetters(["count"]),
}
3、mutations:这是唯一可以改变state数据的途径
mutations: {
add(state, num = 1) {
state.count += num
},
}
(1)直接调用
<button @click="addCount">count+1</button>
methods:{
addCount() {
this.$store.commit("add");
}
}
(2)通过mapMutations方法调用,该方法放在methods中
<button @click="add()">count+1</button>
methods:{
...mapMutations(["add"])
}
(3)mutations传参
mutations: {
addMore(state, num) {
state.count += num
}
}
<button @click="changeCount"></button>
changeCount() {
this.$store.commit("addMore", { num: 5 });
}
4、actions:是异步的mutations,,可以通过$store.dispatch改变state中的数据
actions: {
updateCount(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
}
(1)直接调用
<button @click="update"></button>
methods:{
update() {
this.$store.dispatch("updateCount");
}}
(2) 通过mapActions调用
<button @click="updateCount"></button>
methods:{
...mapActions(["updateCount"])
}
5、modules模块化,如果一个项目中需要使用多个state,可以使用modules对数据进行分类管理
modules: {
name: {
namespaced: true,
state: {
name: 'xiaomihu',
age: 18
},
actions: {
addAge(context) {
setTimeout(() => {
context.commit('add', 5)
}, 1000)
}
},
mutations: {
add(state, num) {
state.age += num
},}
},
}
(1)获取state
//获取方式一
<p>直接获取:{ { $store.state.name.name }}</p>
<p>mapState获取:{ { age }}</p>
...mapState("name", ["age"]),
//获取方式二
//引用createNamespacedHelpers ,实例化时候传入组件名称并解构出来mapState方法,避免与原名称冲突,使用重命名
import { createNamespacedHelpers } from "vuex";
const {mapState: mapStateA} = new createNamespacedHelpers("name");
...mapStateA(["age"])
(2)mutations,action,getters使用方法与它大同小异
//直接获取
<button @click="updateAge"></button>
updateAge() {
this.$store.commit("name/add", 5);
},
//通过mapMutations获取
<button @click="updateAge(5)">借用函数</button>
...mapMutations("name", ["updateAge"])