2、Vuex的項目配置
2.1、爲什麼要分開文件
分開Vuex文件有利於項目文件管理
2.2、項目文件分解圖
- 將Vuex的每個模塊分解爲以上幾個文件
- 總入口 index.js 代碼爲
import Vue from 'vue' import Vuex from 'vuex' import actions from "./actions"; import mutations from "./mutations"; import state from "./state"; import getters from './getters' import user from "./modules/user" Vue.use(Vuex) export default new Vuex.Store({ state, mutations, actions, getters, modules: { user } })
3、Vuex–state
相當於一個數據倉庫
在Vuex的state中定義的數據,可以在各個文件中拿到
3.1、在根Vuex下
- 定義
const state = { appName: 'duck' } export default state
- 獲取
this.$store.state.appName
也可以使用 vuex 的 mapState 獲取
import { mapState } from "vuex"; // 先導入方法 // ...mapState([ // 'appName' // ]) // 或是這樣 ...mapState({ appName: state => state.appName, })
3.2、在模塊下
1.定義(在模塊文件下定義)
const state = { userName: 'pig' } const mutations = {} const actions = {} const getters = {} export default { state, mutations, actions, getters }
- 獲取(this.$store.state.模塊名.模塊內定義的state)
this.$store.state.user.userName
也可以使用 vuex 的 mapState 獲取
import { mapState } from "vuex"; // 先導入方法 ...mapState({ userName: state => state.user.userName })
- 若是在模塊中設置了命名空間,可以使用其他方法
// 在模塊文件中 export default { namespaced: true, // 命名空間,true state, mutations, actions }
// 在使用的文件中 import { createNamespacedHelpers } from "vuex"; const { mapState } = createNamespacedHelpers('user') ...mapState({ userName: state => state.userName // 不需要寫模塊名稱了 })
或是
import { mapState } from "vuex"; ...mapState('user', { // 傳入開啓命名空間的模塊名 userName: state => state.userName })