vuex中modules可以将项目state进行分块,互补干扰。那么在单个module中,action如何调用其他module中action或者根action/mutation/state?
打印action参数:
const actions={
editName(options,payload){
console.log(options)
}
}
运行editName方法,打印结果:
- commit 用于调用mutation,当前模块和其他模块;
- dispatch 用于调用action,当前模块和其他模块;
- getters 用于获取当前模块getter;
- state 用于获取当前模块state;
- rootState 用于获取其它模块state;
- rootGetters 用于获取其他模块getter;
- rootGetters
const actions={
editName({rootGetters},payload){
console.log(rootGetters)
}
}
运行editName:
可以得到,根getters与其他模块getters:Home命名空间下的word
- rootState
const actions={
editName({rootState},payload){
console.log(rootState)
}
}
运行editName,结果:
得到根state下time值以及其它module下的state。
- getters
const getters={
word:state=>`My name is ${state.username}`
}
const actions={
editName({getters},payload){
console.log(getters)
}
}
运行editName,结果:
只会得到当前模块下getters
- state
const state={
username:'wbiokr',
sex:'man'
}
const actions={
editName({state},payload){
console.log(state)
}
}
运行editName,结果:
只会得到当前模块下state
- dispatch
const actions={
editName({dispatch},payload){
dispatch('log')
},
log(){
console.log(123)
}
}
此时运行editName,会运行当前模块下log方法,故结果打印出123。
如果在根空间下定义一个log方法,通过dispatch去调用,则可以通过root参数:
const actions={
editName({dispatch},payload){
dispatch('log',{txt:'hello world'},{root:true})
},
log(){
console.log(123)
}
}
//根空间
actions:{
log({},{txt}){
console.log(txt)
}
}
此时运行editName方法适合,则打印出hello world;
- commit
commit回去触发mutation更新state,如:
const state={
username:'wbiokr',
sex:'man'
}
const actions={
editName({commit,state},payload){
commit('editName','newName')
console.log(state)
}
}
运行editName,结果:
如果想触发其他模块的mutation动态更新state,则需要借助参数root:
根模块index.js
import Home from './modules/home'
import About from './modules/about'
export default {
modules:{
Home,
About,
},
state:{
time:new Date().getTime()
},
getters:{
getFullYear:state=> new Date(state.time).getFullYear()
},
mutations:{
updateTime(state,payload){
state.time=payload.time
}
},
actions:{
updateTime({commit},payload){
commit('updateTime',payload)
},
log({},{txt}){
console.log(txt)
}
},
}
模块about.js
const state={
componey:'one',
}
const mutations={
changeComponey(state,n){
state.componey=n
}
}
const actions={
editName(options,payload){
console.log(options)
}
}
export default {
namespaced:true,
state,
mutations,
actions,
}
模块home.js
const state={
username:'wbiokr',
sex:'man'
}
const getters={
word:state=>`My name is ${state.username}`
}
const mutations={
editName(state,n){
state.username=n
}
}
const actions={
editName({commit,rootState},payload){
commit('About/changeComponey','newComponey',{root:true}) //此处是重点
console.log(rootState.About)
}
}
export default {
namespaced:true,
state,
getters,
mutations,
actions,
}
运行editName方法,结果: