一、vuex 基础结构
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {},
});
// main.js
import store from './store/index'
new Vue({
store,
}).$mount('#app');
1. 数据存放在state属性中;
2. 组件修改数据时,需要遵循单向数据流。
2.1 组件methods调用actions里的异步方法,actions(context,payload),context对象可调用commit方法触发mutations方法。
2.2 mutations里的同步方法用来修改state中的数据,mutations(state,payload)
二、各个模块
1、子模块注册
const store = {
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {},
};
export default store;
import user from "./user";
export default new Vuex.Store({
modules: {
user,
},
});
2、state 存放数据
state: {
name:'',
age:0,
province:'',
city:'',
},
name:this.$store.state.user.name
3、mutations 同步修改数据
mutations: {
changeName(state,payload){
state.name = payload
}
},
handleName(){
this.$store.commit('user/changeName',this.pageName)
}
4、actions 异步修改数据
mutations: {
changeAge(state,payload){
state.age = payload
}
},
actions: {
changeAgeByAction(context,payload){
const ageGet = await xxAgeAxios(payload) // 异步过程
context.commit('changeAge',ageGet)
}
},
handleAge(){
this.$store.dispatch('user/changeAgeByAction',this.pageAge)
}
5、getters 是store的计算属性,所依赖值有改变时重新计算
getters: {
address:(state)=>{
return state.province + state.city
}
},
pageAddress:this.$store.state.getters['user/address']
三、持久化
vuex的数据是响应式的,但在页面刷新时就会丢失,因此可以借助本地存储(缺点数据不响应)实现持久化。
1、直接使用storage
获取state时,其值从storage获取;在mutations中,修改state并存入本地;
state: {
hobby: JSON.parse(sessionStorage.getItem("hobby")) || null,
},
mutations:{
changeHobby(state, payload) {
state.hobby = payload;
sessionStorage.setItem("hobby", JSON.stringify(payload));
},
}
2、借助插件
使用 vuex-persistedstate 只需要修改state值,插件会自动记录变化
安装生产依赖包 npm i vuex-persistedstate --save
引入插件
// store/index.js
import createVuexPersisted from 'vuex-persistedstate'
export default new Vuex.Store({
plugins: [createPersistedState()]
})
设置存储模块,默认localStorage
createVuexPersisted({
storage: window.sessionStorage,
})
使用reducer() 指定存储模块 ,参数val是个对象,包含根模块的state、modules内容
createVuexPersisted({
reducer (val) {
// 指定存储某个模块的数据
return {
user: val.user,
}
}
})
key 属性可以指定本地存储的key值,默认‘vuex’
createVuexPersisted({
key: 'myName',
})