Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vuex命名空间 #117

Open
ddd-000 opened this issue Dec 31, 2021 · 2 comments
Open

vuex命名空间 #117

ddd-000 opened this issue Dec 31, 2021 · 2 comments

Comments

@ddd-000
Copy link

ddd-000 commented Dec 31, 2021

https://vuex.vuejs.org/zh/guide/modules.html#%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4

@ddd-000
Copy link
Author

ddd-000 commented Dec 31, 2021

  1. 作用:
    默认情况下,模块内部的action、mutation和getter是注册在全局命名空间的,这样使得多个模块能够对同一mutation或action作出响应。可以通过命名空间使模块具有更高的封装性和复用性。
  2. 解决什么问题
    vuex是单一状态树,所有状态包含在一个大对象中,随着项目的扩展会变得非常臃肿。方法名字重复会导致报错或者action执行多次的问题。这时候就可以通过命名空间使其独立。
  3. 使用:namespaced: true
const moduleA ={
    namespaced:true,  //开启namespace:true,该模块就成为命名空间模块了
    state:{
        count:10,
        countA:888
    },
    getters:{...},
    mutations:{...},
    actions:{...}
}

//or
const state = {}
const actions = {}
const mutations = {}
const getters = {}
export default {
  namespaced:true,
  state,
  actions,
  mutations
}
  • state
//1、基本方式:
    this.$store.state.moduleA.countA
//2、mapState辅助函数方式:
    ...mapState({
        count:state=>state.moduleB.countB
    })
  • getters
//共有三种方式,如下:
//1.
commonGetter(){
    this.$store.getters['moduleA/moduleAGetter']
},
//2.
...mapGetters('moduleA',['moduleAGetter']),此处的moduleA,不是以前缀的形式出现!!!
//3.别名状态下
...mapGetters({
    paramGetter:'moduleA/moduleAGetter'
})
  • mutations
//共有三种方式,如下:
//1,3加个前缀moduleA/,都可以实现。2使用辅助函数未变名称的特殊点!!!
//1.
commonMutation(){
    this.$store.commit('moduleA/moduleAMutation');
},
//2.
...mapMutations('moduleA',['moduleAMutation']),
//3.别名状态下
...mapMutations({
    changeNameMutation:'moduleA/moduleAMutation'
})
  • actions
//共有三种方式,如下:
//1,3加个前缀moduleA/,都可以实现。2使用辅助函数未变名称的特殊点!!!
//1.
commonAction(){
    this.$store.dispatch('moduleA/moduleAAction')
},
//2.
...mapActions('moduleA',['moduleAAction']),
//3.别名状态下
...mapActions({
    changeNameAction:'moduleA/moduleAAction'
})

@ddd-000
Copy link
Author

ddd-000 commented Dec 31, 2021

模块化+命名空间数据独立后,模块间如何通过action相互访问?

const { commit, dispatch, state, rootState, rootGetters } = store
  1. 访问其他模块的state
    rootState --- 可以拿到根state
    rootState.模块名 --- 就可以拿到其他模块
  2. 其他模块actions和mutation调用
    dispatch('模块A的 action路径', {}, {root: true}) --- 带有命名空间的模块B调用带有命名空间的模块A的action
    commit('模块A的 mutation路径', data, {root: true}) --- 调用其他模块的 mutations
  3. 访问其他模块getters
    rootGetters['模块名/方法']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant