vuex 模块化开发
vuex 获取属性 需要使用 computed 才是响应式的 针对 基本数据类型
const profile = computed(() => store.state.user.profile)
复杂数据类型 { } [ ] – proxy
import user from './modules/user'
export default createStore({
state: {},
mutations: {},
actions: {},
getters: {},
modules: { user },
}
使用方式
1 直接使用
{{ $store.state.userName}}
{{ $store.getters.newName}}
$store.dispatch("aIncrement",1111)
$store.commit("bIncrement",1111)
2 模块中
只有 state 区分模块 其他的都是全局的
$store.state.user.userName
$store.getters.newName A模块中的getters 无命名空间
有命名空间的模块
$store.getters["B/newName"]
模块中 开启了命名空间
store.commit("B/updateName")
store.dispatch("B/updateName")
mutations 中
(state, payLoad)
actions 中 context 可以 log 找出需要的 rootState, state, commit,dispatch,getters
(context, payLoad)
getters 中
(state, getters)
vuex-持久化–vuex-persistedstate 持久化 插件
vuex中存储且需要本地存储 默认 localStorage 存储
安装
npm i vuex-persistedstate
import createPersistedstate from 'vuex-persistedstate'
// vuex index 中 配置插件
plugins: [
// 将本地存储的数据持久化到store中 默认 localStorage
createPersistedstate({
// 本地存储的名字
key:'eRabbit-client-pc',
// 指定存储的模块
paths:['user','cart'],
// 也可以 指定 存储哪些数据 不写 paths 存储 state中所有数据 或者部分 state.user state.cart 等
// render(state) {
// return { ...state }
// },
}),
// 想要分别指定 local session 可以创建 不同的 createPersistedstate
createPersistedstate({
// 本地存储的名字
key: 'general-background',
// 更改默认存储方式
storage: window.sessionStorage,
paths: ['common'],
}),
]