這需要一個完整的例子。
我先依照先前講的把程式碼先準備好
準備了兩個頁面: User, Users
為了示範上面用一個 nav 來切換。
切換到 User 時,hard code 了它的 id。
(其實之後也可以做在 Users 上面的 link)
可以到 mockAPI 上面設定一組。
src/store/user/index.js
import actions from './actions';
export default {
actions,
state: {
one: {},
list: []
},
mutations: {
user (state, payload) {
state.one = payload
},
users (state, payload) {
state.list = payload
}
},
getters: {
user (state) {
return state.one;
},
users (state) {
return state.list;
},
},
};
src/store/user/actions.js
import backendAPI from '@/utility/backendAPI';
export default {
async fetchUser({ commit }, id) {
const res = await backendAPI.GET(`/user/${id}`);
commit('user', res.data);
},
async fetchUsers({ commit }) {
const res = await backendAPI.GET('/user');
commit('users', res.data);
},
async createUser({ dispatch }, { id, name, avatar }) {
const res = await dispatch('uploadFile');
await backendAPI.POST(`/user`, {
name,
avatar: res.data,
});
},
async updateUser({ dispatch }, { id, name, avatar }) {
const res = await dispatch('uploadFile');
await backendAPI.PUT(`/user/${id}`, {
name,
avatar: res.data,
});
},
async deleteUser(context, id) {
await backendAPI.DELETE(`/user/${id}`);
},
};
src/store/actions.js
import backendAPI from '@/utility/backendAPI';
export default {
async uploadFile({ commit, getters }, file) {
const res = await backendAPI.formDataPOST('/file', getters.file);
commit('file', res.data);
}
};
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import user from './user';
Vue.use(Vuex);
export default new Vuex.Store({
actions,
state: {
file: null
},
mutations: {
file(state, payload) {
state.file = payload;
}
},
getters: {
file(state) {
return state.file;
}
},
modules: {
user
},
});
import Vue from 'vue';
import VueRouter from 'vue-router';
import User from '../views/User.vue';
import Users from '../views/Users.vue';
import store from '../store';
Vue.use(VueRouter);
const routes = [
{
path: '/user',
name: 'Users',
component: Users,
beforeEnter: (to, from, next) => {
store.dispatch('fetchUsers')
next()
}
},
{
path: '/user/:id',
name: 'User',
component: User,
beforeEnter: (to, from, next) => {
store.dispatch('fetchUser', to.params.id)
next()
}
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
router.beforeEach((to, from, next) => {
console.warn(`${from.path} -> ${to.path}`);
next()
})
export default router;
App.vue
<div id="app">
<div id="nav">
<router-link :to="{ name: 'Users' }">users</router-link> |
<router-link :to="{ name: 'User', params: { id: 1 } }">user1</router-link>
</div>
<router-view />
</div>
src/User.vue
先確認可以把值順利顯示出來。
<div>
<pre>{{ $store.getters.user }}</pre>
</div>
export default {
name: 'User',
};
src/views/Users.vue
<div>
<pre>{{ $store.getters.users }}</pre>
</div>
export default {
name: 'Users',
};