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 函數