命名空间
认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
state: () => ({ ... }),
getters: {
isAdmin () { ... }
},
actions: {
login () { ... }
},
mutations: {
login () { ... }
},
modules: {
myPage: {
state: () => ({ ... }),
getters: {
profile () { ... }
}
},
posts: {
namespaced: true,
state: () => ({ ... }),
getters: {
popular () { ... }
}
}
}
}
}
})
基于vuex实现在dispatch派发请求前后做一些事情的插件
核心
const NAMESPAED = 'myLoading'
const createLoadingPlugin = ({ namespaced = NAMESPAED }) => {
return store => {
store.registerModule(namespaced, {
namespaced:true,
state:{
loding:{}
},
mutations:{
show(state,value){
state.loding={
[value]:true
}
},
hide(state,value){
state.loding={
[value]:false
}
}
},
actions:{
}
})
store.subscribeAction({
before: (action, state) => {
console.log(`before action ${action.type}`)
store.commit(namespaced+'/show',action.type)
},
after: (action, state) => {
console.log(`after action ${action.type}`)
store.commit(namespaced+'/hide',action.type)
}
})
}
}
export default createLoadingPlugin
我们需要在修改发请求改 this.$store.state.numder 的时候加一个状态
就可以先 this.store.dispatch('oneAsync') 发请求那数据
这时 subscribeAction里面的before会触发
当派发结束 this.$store.state.numder被修改完 after会触发
加载状态开始和结束的值使用什么呢?this. $store.state.myLoading.loding['oneAsync']
new Vuex.Store({
plugins:[createLoadingPlugin],
state:{
number: 1,
},
mutations:{
oneAsync(state,payload){
state.number=state.number.payload
},
actions:{
oneAsync({commit},payload){
return new Promise((resolve,reject)=>{
window.setTimeout(()=>{
resolve()
commit('oneAsync',payload)
})
},2000)
}
}
}
})
Vuex持久化存储之vuex-persist