【vue】vuex中modules的基本用法

1,什么时候用modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
在模块中使用:namespaced: true, 命名空间,添加之后,当前模块下的标识符可以和其它模块相同,用于解决不同模块的命名冲突问题

2,store文件结构

3.1 index.js中手动引入modules

import Vue from 'vue'
import Vuex from 'vuex'

import bus from './modules/bus'
import app from './modules/app'

const path = require('path')

Vue.use(Vuex)

let store = new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    namespaced: true,
    app,
    bus
  }
});

export default store

3.2 index.js 中动态引入modules

import Vue from 'vue'
import Vuex from 'vuex'
const path = require('path')

Vue.use(Vuex)

const files = require.context('./modules', false, /\.js$/)
let modules = {}
files.keys().forEach(key => {
  let name = path.basename(key, '.js')
  modules[name] = files(key).default || files(key)
})

let store = new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules
});

export default store

4,app.js 文件中代码

let user = {
  namespaced: true,
  state: {},
  mutations: {
    setUser(state, val) {
      state.user = val;
    }
  },
  getters: {},
  actions: {
    setName(state, val) {
      return new Promise(resolve => {
        setTimeout(function () {
          state.user = val;
          resolve(state.user);
        }, 2000)
      })
    }
  }
}

export default user;

 5,配置main.js,挂载store

new Vue({
  el: '#app',
  router,
  store,
  components: { App: App },
  template: '<App/>'
})

6,vue中使用

    // commit 执行mutations里的方法,同步操作
    this.$store.commit('app/setUser', {name: '张三'});
    console.log(this.user.name);
    // dispatch 执行actions里的方法,异步操作
    this.$store.dispatch('app/setName', {name: '李四'}).then(res => {
      console.log(res.name);
    })

7,js中使用

// 引入 这里的store 就相当于页面中的 this.$store
import store from '@/store'

export const setCurUser = (user) => {
    let curUser = store.app.user
    if(!curUser) {
        store.commit("app/setUser", user)
        return user
    }
    
    return curUser
}

注意:

1,vue和vuex的版本搭配

vue2使用vuex3;vue3使用vuex4. 否则会出现this.$store为undefined错误

延伸:

1,vuex的五种状态 state、getter、mutation、action、module

state:所有共享数据统一放到state中,与data类似

mutation: 类似于事件,用于改变状态

action: 和mutation相似,但是action是异步操作

getter: 类似vue中的computed,进行缓存,形成新的数据

modules: 分模块,大型项目一个对象管理会很臃肿

猜你喜欢

转载自blog.csdn.net/u013517229/article/details/127906004