vuex 模块化的使用 , 和 不同 数据之间的相互调用

index.js 文件, vuex 的核心文件

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules.js'
import getters from './getters.js'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {},
    mutations: {},
    actions: {},
    modules,
    getters,
})

可以发现 

modules
getters
是从外部导入的
没错, vuex 中就只放这四个就行了

下面是 index.js 导入的 modules 干的事情
import xibao from './modules/xibao.js'

export default {
  xibao: xibao
}

然后, 导入的 xibao.js 文件

export default {
  namespaced: true,
  state: () => ({
    deviceInfo: JSON.parse(localStorage.getItem('deviceInfo')) || {}
  }),
  mutations: {
    // 保存设备信息
    save_deviceInfo(state, deviceInfo) {
      // ...       
    }
  }
}
namespaced: 命名空间, 防止变量名称冲突

getters.js 这个模块
export default {
  // 洗宝
  deviceInfo: state => state.xibao.deviceInfo,
}

作用吗 ? 就是 快捷 获取到 子模块文件中 的 数据


关于 vuex 中各种数据的相互调用

1. commit 调用 data 中的数据
在cmmmit 的 函数 中 第一个参数 为 state , 通过 state . 的形式 就能 访问 到 state 中的数据
比如说
fn(state) {
  // 这里的state 就代表当前文件中的 state 的状态
}

2. dispatch 中 获取 state 中的参数
  可以通过 解构 的方式 获取 到 commit , rootState , 分别代表 触发 mutations中的 commit 和 state 中的根数据
  fn ({rootState, commit}) {}

3. commit 调用mutations中的函数
直接使用 this.commi() 触发 , this指向当前的vuex



调用模块中的方法
比如说调用 a 模块中的 fn


this.$store.commit( 'a/fn', params )
a/fn 指向的就是 a 模块下的 fn 函数

posted @ 2021-01-22 18:42  深海里的星星i  阅读(1520)  评论(0)    收藏  举报