vuex中的modules

vuex中将数据模块化

1. 在vuex中将组件模块化,注意:加属性:namespaced:true;命名空间

const downloade = {
    namespaced: true, //命名空间为true
    state: {
      personList: [],
    },
    getters: {
      newPerson (state, getters) {
        return state.personList.map((item, index) => {
          if(index == 0) {
            return '@@@@' + item + getters.a
          }else if(index < 3) {
            return '###' + item + '$$$'+ getters.a
          }else {
            return '++' + item + '***'+ getters.a
          }
        })
      },
      a () {
        return '1111'
      }
    },
    mutations: {
      changePersonList (state, addValue) {
        state.personList.push(addValue)
      },
    },
    actions: {
      changeP (ctx, addValue) {
        setTimeout( () => {
          ctx.commit('changePersonList', addValue);//触发mutations中的changePersonList函数
        }, 1000)
       
      }
    }
}
const personal = {
    namespaced: true, //命名空间为true
    state: {
      login: false,
    },
    getters: {

    },
    mutations: {
      changeLogin (state, value) {
        state.login = value
      }
    },
    actions: {

    }
}

(2)在Store中加modules属性

export default new Vuex.Store({
  strict: true, // 严格模式
  state: {
    
    name: 'zhu',
    age: 23,
    personList: [],
  },
  getters: {

  },
  mutations: {


  },
  actions: {

  },
  modules: {
    downloade,
    personal
  }
})

2. 组件中的使用:

(1)组件中用来触发vuex中的函数的commit和dispatch:在函数前面加模块名,哪个模块下的函数

this.$store.commit('personal/changeLogin',this.loginFlag)
 this.$store.dispatch('download/changeP', this.addValue)

(2)展开运算符中,state是对象,state下的downloade,download下数据。

 ...mapState({
        personList: state => state.download.personList, 
      }),

总之,与state相关的,在state后加命名空间,为什么呢?我们来看下state对象

1)this.$store 即 vuex中的Store,state对象就是在State下;

2)state对象:age和name正是Store下的state属性中的属性,而download和personal正是命名空间的名字。

vuex中的modules_第1张图片

3)在download和personal下面:又有自己的state下的值

结论:modules使得组件模块化,我们应该注意到的是:将vuex中数据池进行了模块化,数据结构:

vuex中的modules_第2张图片

 

(3)展开运算符中,前面加一个属性,‘download’,告诉mapGetters,newPerson计算属性是download下的getters中的。

...mapGetters ('download',['newPerson'])

3. 将每个组件所需要的vuex值,抽离出来放在一个文件中,然后在store.js中引入。

(1)store.js中:

在src文件夹下的assets文件夹的vuex文件夹下的download.js文件和personal.js文件

将组件所需的vuex数据对象导出:

export default {
  namespaced: true, //命名空间为true
  state: {
    login: false,
  },
  getters: {

  },
  mutations: {
    changeLogin (state, value) {
      state.login = value
    }
  },
  actions: {

  }
}

 

你可能感兴趣的:(Vue,vuex)