vuex 是 实现 跨组件通信 技术解决方案
五个核心概念:state mutations actions getters modules
1.vuex的安装
注意:vue2对应的vuex版本3,vue3对应的vuex版本4(vue3建议使用Pinia)
yarn add vuex -S
npm install vuex -S
2.vuex的初始化(vue2的)
// store/index.js 组件
import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from './moduleA';
Vue.use(Vuex)// 给组件 添加 $store
const store = new Vuex.Store({
state: {
val: '999',
},
getters: {
getVal: state => state.val,
},
mutations: {
setVal(state, val) {
state.val = val;
},
},
actions: {
setTimeVal(context, val) {
setTimeout(() => {
context.commit('setVal', val);
}, 1000);
},
},
modules: {
moduleA,
},
})
export default store
// main.js 引入及注册
import Vue from 'vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
3.state
作用:定义 共享的数据源
使用:
直接使用
this.$store.state.变量名
映射使用
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['state变量名']),// 不能改名
...mapState({ // 如果你想将一个 getter 属性另取一个名字,使用对象形式:
新属性名: 'state中变量名'
})
}
}
4.getters
作用:vuex 的 计算属性,根据 state 中 数据源 计算而得到,类似computed、优势 带缓存
使用:
直接使用
this.$store.getters.计算属性的名字
映射使用
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['getters中计算属性的名字']), // 不能改名
...mapGetters({ // 如果你想将一个 getter 属性另取一个名字,使用对象形式:
新属性名:'gettes里面对应的方法'
})
}
}
5.mutations
作用:唯一 可以 同步 修改 state的 地方
使用:
直接使用
this.$store.commit('mutations中的函数名', 传值)
映射使用
import { mapMutations } from 'vuex'
// 注意是映射到methods
export default {
methods: {
...mapMutations(['mutations中函数名']), // 不能改名
...mapMutations({ // 如果你想将一个 getter 属性另取一个名字,使用对象形式:
新属性名:'vuex Mutation里面的方法名'
})
}
}
6.actions
作用:异步 的 修改 state,但其不能直接改,最终必须 commit 到 指定 mutations 中方法来修改state
需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
使用:
直接使用
this.$store.dispatch('actions中的函数名', 传值)
映射使用
import { mapActions } from 'vuex'
// 注意是映射到methods
export default {
methods: {
...mapActions(['actions函数名']), // 不能改名
...mapActions({ // 如果你想将一个 getter 属性另取一个名字,使用对象形式:
新属性名:'Actions里面的方法名',
.....
})
}
}
7.modules
作用:当一个文件中存在大量的数据时,不方便维护,可以按需求拆分成多个模块
定义
定义模块文件
const moduleA = {
namespaced: true, // 开启命名空间(最好开启命名空间)
state: {
val1: '',
},
getters: {
val1: state => state.val1,
},
mutations: {
setVal1(state, val) {
state.val1 = val;
},
},
actions: {
setTimeVal1(context, val) {
setTimeout(() => {
context.commit('setVal1', val);
}, 1000);
},
},
};
export default moduleA;
vuex初始化modules导入对应的模块
import moduleA from './moduleA';
const store = new Vuex.Store({
modules: {
moduleA,
},
})
使用
直接使用
// state 的使用方式
this.$store.state.模块名.模块下的变量名
// getters 的使用方式
this.$store.getters['模块名/模块下的getters的名字']
// mutation 的使用方式
this.$store.commit('模块名/模块下的mutation的名字', 传值)
// action 的使用方式
this.$store.dispatch('模块名/模块下的action的名字', 传值)
映射
// state 及 getters 的使用方式
computed: {
...mapState('模块名', ['模块下的变量名']),
...mapGetters('模块名', ['模块下的getters的名字']),
}
// mutation 及 action 的使用方式
methods: {
...mapMutations('模块名', ['模块下的mutation的名字']),
...mapActions('模块名', ['模块下的action的名字'])
}
// 使用
this.模块变量名
//demo
export default {
computed: {
...mapState('moduleA', ['val1']),
...mapGetters('moduleA', ['val1']),
},
methods: {
...mapMutations('moduleA', ['setVal1']),
...mapActions('moduleA', ['setTimeVal']),
vuexFn() {
// 分模块
// state
console.log('val1', this.val1);
// getters
console.log('gettersval1', this.val1);
// mutations
this.setVal1('99999');
// action
this.setTimeVal('666666')
},
},
};
8.持久化存储
通过使用 vuex-persistedstate 实现持久化存储
使用方法:
安装
npm install vuex-persistedstate --save
使用
export default createStore({
state: { },
mutations: { },
actions: { },
modules: { },
plugins: [
// 把vuex的数据存储到sessionStorage
createPersistedState({
paths:['moduleA'],
storage: window.sessionStorage,
}),
],
})
API
key: 存储持久状态的key(默认vuex)
paths :默认存储全部,可以手动设置存储模块,默认([]),如:paths:['moduleA']。
reducer :一个函数,将被调用来基于给定的路径持久化的状态。默认包含这些值。
subscriber :一个被调用来设置突变订阅的函数。默认为store => handler => store.subscribe(handler)
storage :而不是(或与)getState和setState。默认为localStorage。
getState :将被调用以重新水化先前持久状态的函数。默认使用storage。
setState :将被调用来保持给定状态的函数。默认使用storage。
filter :将被调用来过滤将setState最终触发存储的任何突变的函数。默认为() => true
注意事项
state、getters 都是 映射 在 组件 的 computed 中
mutations、actions 都是 映射 在 组件 的 methods 中
mutations 和 actions的区别
相同点:本质 都是 函数
不同点:
mutations: 唯一 并且 同步 修改 state的
actions: 异步 修改 state的、但它不能直接改,最终 必须 commit 到 mutations 上
第一个形参的区别:mutations 第一个 形参 是 state,actions 第一个 形参 是 store
何时需要使用vuex?
多个组件需要 共享 数据 的时候,如果组件是 父子关系,老老实实 用 父传子 或 子传父