iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0

這需要一個完整的例子。

我先依照先前講的把程式碼先準備好

先看畫面

準備了兩個頁面: User, Users
為了示範上面用一個 nav 來切換。

切換到 User 時,hard code 了它的 id。
(其實之後也可以做在 Users 上面的 link)

準備 API

可以到 mockAPI 上面設定一組。

準備程式碼

Store

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
  },
});

Router

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;

Component

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',
};

上一篇
其它的 lifecycle 或 vue router 的 hook
下一篇
用 event 來準備傳給後端的 data
系列文
Vue.js 進階心法30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言