|
| 1 | +let store = require('begin-build/store'); |
| 2 | + |
| 3 | +// Optional things to do in init |
| 4 | +let api = require('begin-build/api'); |
| 5 | +let { ready } = require('begin-build/router'); |
| 6 | + |
| 7 | +/* |
| 8 | + * How to set up a store module: |
| 9 | + * - store() will namespace this Vuex store module by the name of the file |
| 10 | + * - keep module.id as the first argument to store() |
| 11 | + * - index.js inside subdirectories will become namespaced to the parent directory name |
| 12 | + * - if this is in a subdirectory of the store directory this will be a pathed submodule |
| 13 | + */ |
| 14 | +module.exports = store(module.id, { |
| 15 | + state: { |
| 16 | + example: false, |
| 17 | + }, |
| 18 | + |
| 19 | + mutations: { |
| 20 | + setExample(state, data) { |
| 21 | + state.example = data; |
| 22 | + }, |
| 23 | + |
| 24 | + toggleExample(state) { |
| 25 | + state.example = !state.example; |
| 26 | + }, |
| 27 | + }, |
| 28 | + |
| 29 | + getters: { |
| 30 | + getExample(state) { |
| 31 | + return state.example; |
| 32 | + }, |
| 33 | + }, |
| 34 | + |
| 35 | + actions: { |
| 36 | + // init is a special action that will be automatically executed when this store is initialized |
| 37 | + async init({ commit, getters }) { |
| 38 | + |
| 39 | + // run some async function like a request using axios |
| 40 | + let { data } = await api.get('example/endpoint'); |
| 41 | + |
| 42 | + // commit mutations or dispatch actions |
| 43 | + commit('setExample', data); |
| 44 | + |
| 45 | + // do things with router and the store |
| 46 | + let router = await ready; |
| 47 | + router.beforeEach((route, redirect, next) => { |
| 48 | + if (route.matched.some(record => record.meta.example)) { |
| 49 | + commit('setExample', true); |
| 50 | + |
| 51 | + // view the store with getters |
| 52 | + } else if(getters.example) { |
| 53 | + commit('toggleExample'); |
| 54 | + } |
| 55 | + next(); |
| 56 | + }); |
| 57 | + }, |
| 58 | + }, |
| 59 | +}); |
0 commit comments