vuex的模塊化使用


store文件如下

 

 

 1.modules下文件是模塊化的划分,里面的js有state,action,mutations.然后通過

export default {
namespaced: true,
state,
mutations,
actions
}

方式導出。

2.index.js中導出的格式如下

new Vuex.Store({
  modules:{
      app:{
          namespaced:true,
          state:{},
          mutations:{},
          actions:{}
      },
      ...
  },
  getters:{
    sidebar: state => state.app.sidebar,
    size: state => state.app.size,
    device: state => state.app.device,
    sjhnum: state => state.shangjinhui.num,
    ...
  }
})

所以index.js中需要先對modules進行處理,通過require.context獲取modules下所有js文件,如下

const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')     
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default                               
  return modules
}, {})

然后對getters的處理可以摘出來放到單獨js里。

因為modules的處理,下面相對於普通的使用方式多了個命名空間

3.獲取store里的數據

1 this.$store.state.命名空間.

import { mapState } from 'vuex';

computed:{

...mapGetters({

  'getters里定義的key(其實對應的state值)'

})

}

4修改store值

this.$store.dispatch('命名空間/actions里的函數名',參數數據),
this.$store.commit('命名空間/mutations里的函數名',參數數據)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM