天天看点

认识vuex中的modules

本文参考文献

store/modules/user.js
export default{
    // 通过添加namespaced将actions,mutations,getters限定在模块命名空间中
    // 当所有的actions, mutations, getters 都被限定到模块的命名空间下,我们dispatch actions, commit mutations 都需要用到命名空间。
    // dispacth("changeName"),  就要变成 dispatch("login/changeName"); getters.localJobTitle 就要变成 getters["login/localJobTitle"]
    namespaced:true,
    state:{
        userName:'obama',
    },
    getters:{
        // 通过rootState,rootGetters来获取根store中的state和getters
        allName(state,getters,rootState,rootGetters){
            return state.userName + rootState.secondName;
        }
    },
    actions:{

    },
    mutations:{
        changeName(state,newName){
            state.userName = newName;
        },
    }
}
           
store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 引入user 模块
import user from './modules/user';
export default new Vuex.Store({
    state:{
        secondName:'LI'
    },
    mutations:{

    },
    getters:{

    },
    actions:{

    },
    // 通过modules引入到store中
    modules:{
        user
    }
})
           
HelloWorld.vue
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- 从modules--user中获取到的name -->
    <p>{{userName}}</p>
    <button @click="changeName">改变名字</button>
    <p :title="allName">{{allName}}</p>
  </div>
</template>

<script>
import { mapGetters , mapMutations } from 'vuex';
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
    }
  },
  computed:{
    userName:function(){
      // 有modules 之后,state user 的命名空间(模块)下。所以属性名前面必须加模块名(命名空间),组件中通过 this.$store.state.模块名.属性名
      return this.$store.state.user.userName;
    },
    // ...mapGetters(['allName']) //modules中没有添加namespaced
    ...mapGetters('user',['allName']), //添加了namespaced
  },
  methods:{
    changeName(){
      // this.$store.commit('changeName','Trump'); //modules中没有添加namespaced
      this.$store.commit('user/changeName','Trump'); //添加了namespaced
      // 在模块中,state 是被限制到模块的命名空间下,需要命名空间才能访问。 但actions 和mutations, 其实还有 getters 却没有被限制,在默认情况下,
      // 它们是注册到全局命名空间下的,所谓的注册到全局命名空间下,其实就是我们访问它们的方式和原来没有module 的时候是一样的。比如没有module 的时
      // 候,this.$store.dispatch(“actions”), 现在有了modules, actions 也写在了module 下面(changeName 写到了user目录下的index.js中),我们
      // 仍然可以这么写,this.$store.commit(“changeName”), 组件中的getters, 也是通过 this.$store.getters.module中getters 来获取。
    }
  }
}
</script>