目录
定义:
Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式发生变化。可以理解为:将多个组件共享的变量全部存储在一个对象里面,然后将这个对象放在顶层的 Vue 实例中,让其他组件可以使用,它最大的特点是响应式。
用法:
store 对象中存放的东西是固定的,有5个:state、mutations、actions、getters、modules
1.state的定义
const store = new Vuex.Store({
state:{
id:"123",
counter:100
}
})
2.state的调用
直接使用
this.$store.state.id
this.$store.state.counter
或者按需导入mapState函数,如下
import { mapState } from 'vue';
computed:{ // 注意:当前组件需要的全局数据,映射为当前组件的computed属性
...mapState(["id","counter"])
}
3.mutation的作用
在组件中需要对 state 的状态信息进行修改,要先拿到 store 对象,然后通过 commit 提交 mutations 中的方法。
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
mutations:{ // 定义一些方法
increment(state, num){
state.counter = state.counter + num;
}
decrement(state){
state.counter--;
}
}
4.mutation的调用
直接定义
methods:{
sub(){
this.$store.commit('decrement')
},
add(){
this.$store.commit('increment',10)
}
}
使用辅助函数mapMutation
import { mapMutation } from 'vue';
methods:{
...mapMutation(['increment','decrement']),
sub(){
this.$store.commit('decrement')
},
add(){
this.$store.commit('increment',10)
}
}
5.actions异步操作
将mutation中的减法操作decrement改为异步
actions:{
asyncReduce(context){
setTimeout(()=>{
context.commit("decrement")
}, 1000)
}
}
6.actions的调用
使用dispatch直接调用
this.$store.dispatch('asyncReduce')
使用辅助函数mapActions
import { mapActions } from 'vue';
methods:{
...mapActions(["asyncReduce"]),
reduceNum(){
this.asyncReduce();
}
}
7.getters
在vuex中的Store仓库里,state就是用来存放数据,而getters类似于computed计算属性,也可以对数据进行过滤处理。
先在store文件夹下新建state.js文件和getters.js文件,并在index.js下引入
import state from './state';
import getters from './getters';
Vue.use(Vuex);
const store = new Vuex.Store({
state,
getters
})
// 假设1代表初级,2代表中级,3代表高级,在state中存储level值为1或2或3
// 先在state.js中增加userStatus变量
const state = {
userStatus: 2
}
export default state;
// 想在页面中获取对应等级就需要进行转换,此时就需要用到getters
const getters ={
memberInfo(state){
switch (state.userStatus) {
case 0:
return "普通会员"
break;
case 1:
return "vip会员"
break;
case 2:
return "高级会员"
break;
default:
break;
}
}
}
export default getters;
// 补充一种比较常见的写法:
const getters = {
name: state => state.user.name
avatar: avatar => state.user.avatar
};
export default getters;
8.modules
当遇见大型项目时,数据量大,store就会显得很臃肿。为了解决这个问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间的——这样使得多个模块能够对同一个 action 或 mutation 作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
this.$store.state.cityModules.cityname
注意
版本问题:vue 的 2.x 版本对应 vuex 的 3.x 版本,vue 的 3.x 版本对应 vuex 的 4.x 版本