模組
在 src/store/modules 資料夾新增 record.js 模組。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | import axios from 'axios';
 export default {
 namespaced: true,
 state: {
 
 },
 mutations: {
 
 },
 actions: {
 
 },
 };
 
 | 
在 src/store/ 資料夾的 index.js 檔引入模組。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 
 | import Vue from 'vue';import Vuex from 'vuex';
 import record from './modules/record';
 
 Vue.use(Vuex);
 
 export default new Vuex.Store({
 namespaced: true,
 modules: {
 record,
 },
 state: {
 loading: false,
 },
 mutations: {
 
 },
 actions: {
 
 },
 });
 
 | 
命名空間
在元件分發模組的動作,在 dispatch() 的第一個參數引入命名空間。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | export default {methods: {
 fetchRecords() {
 this.$store.dispatch('record/fetchRecords', {
 url: '/users/me/records',
 })
 .then(({ data }) => {
 
 });
 },
 },
 };
 
 | 
在元件分發根目錄模組的動作,在 dispatch() 的第三個參數引入如下物件。
| 12
 3
 4
 5
 6
 7
 
 | export default {methods: {
 setLoading() {
 context.dispatch('setLoading', false, { root: true });
 },
 },
 };
 
 | 
其他
使用輔助函數,在元件獲取多個倉庫(store)狀態。
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | import { mapState } from 'vuex';
 export default {
 computed: {
 ...mapState([
 'loading',
 ]),
 },
 };
 
 | 
參考資料