刷新数据不丢失
1.vue持久化 vue-presits插件
2.放在缓存中
vuex流程
引用vuex=>注册vuex(Vue.use(vuex))=>new vuex=>导出放在vue实例上
vuex 相关属性
1.state,mutation,action,modules,getter
2.mutation触发commit action触发是dispatch
modules中nameSpace用法以及传参相关方法
nameSpace:true 调用dispatch()
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
state: {...}, // 模块内的状态已经是嵌套的,namespaced不会有影响
getters: { // 每一条注释为调用方法
isAdmin () { ... } // getters['account/isAdmin']
},
actions: {
login () {...} // dispatch('account/login')
},
mutations: {
login () {...} // commit('account/login')
},
modules: { // 继承父模块的命名空间
myPage : {
state: {...},
getters: {
profile () {...} // getters['account/profile']
}
},
posts: { // 进一步嵌套命名空间
namespaced: true,
getters: {
popular () {...} // getters['account/posts/popular']
}
}
}
}
}
})
如果你希望使用全局state和getter,roorState和rootGetter会作为第三和第四参数传入getter,也会通过context对象的属性传入action
若需要在全局命名空间内分发action或者提交mutation,将{ root: true }作为第三参数传给dispatch或commit即可。
modules: {
foo: {
namespaced: true,
getters: {
// 在这个被命名的模块里,getters被局部化了
// 你可以使用getter的第四个参数来调用 'rootGetters'
someGetter (state, getters, rootSate, rootGetters) {
getters.someOtherGetter // -> 局部的getter, ‘foo/someOtherGetter’
rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter'
}
},
actions: {
// 在这个模块里,dispatch和commit也被局部化了
// 他们可以接受root属性以访问跟dispatch和commit
smoeActino ({dispatch, commit, getters, rootGetters }) {
getters.someGetter // 'foo/someGetter'
rootGetters.someGetter // 'someGetter'
dispatch('someOtherAction') // 'foo/someOtherAction'
dispatch('someOtherAction', null, {root: true}) // => ‘someOtherAction’
commit('someMutation') // 'foo/someMutation'
commit('someMutation', null, { root: true }) // someMutation
}
}
}
}
mutation,action的区别
1.mutation专注于修改state,而action专注于业务代码,异步请求
2.mutation 必须同步执行,action可以异步
getter和state区别
就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
vuex为什么不建议在action中修改state
当某种类型的action只有一个声明时,action的回调会被当作普通函数执行,而当如果有多个声明时,它们是被视为Promise实例,并且用Promise.all执行(Promise.all在执行Promise时是不保证顺序的)