接下來我們要針對refreshList()
進行介紹,此方法是從後端API撈取員工資料,因為資料需要在多個組件之間共享,須透過Vuex管理狀態,由其向後端請求,經存入狀態後,網頁畫面才更新。
由上面的說明可知,Vuex在其中扮演關鍵角色,因此需要設定Vuex store,來引入Vuex模組物件(module object),並將該設定檔放置於src/store/index.js
,並於src/main.js
掛載Vuex狀態管理,參考如下。
// store/index.js
import { createStore } from 'vuex';
import employee from './employee.module'; // 引入Vuex模組物件(module object)設定
const store = createStore({
// store的模組區
modules: {
employee // 模組名稱是employee
}
});
export default store;
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store'; // 引入Vuex store
const app = createApp(App);
app.use(router)
app.use(store); // 掛載Vuex狀態管理
app.mount('#app'); // 掛載到 index.html 的 <div id="app">
掛載完成後,回到refreshList()
方法,拆分其步驟如下
store.dispatch(...)
發出非同步請求(須等待處理時間,資料不會立即回來),向後端API取得員工資料FETCH_EMPLOYEES
,來負責處理 API 邏輯page
、page_size
等// src/views/Employee.vue
<script>
export default {
methods: {
refreshList() {
store.dispatch(`employee/${FETCH_EMPLOYEES}`, {
page: this.currentPage,
page_size: this.pageSize
});
}
}
};
</script>
在這個方法中,也充分展現出Vuex單向資料流(one-way data flow)的特色,即網頁使用者觸發事件後,再由元件方法(method)觸發Vuex發出請求,執行完動作(action),經Vuex改變之狀態(state)後,網頁畫面才自動更新。
實際上,上面僅簡單地介紹Vuex資料流,Vuex在完成這個流程之中,還涉及到許多細節,以下將慢慢帶出相關細節的介紹。首先,為了讓refreshList()
方法能順利執行,我們還需要在<script>
區塊中補充相關設定,參考如下。
// src/views/Employee.vue
<script>
import store from "@/store"; // 引入Vuex store,用於dispatch動作
import { mapGetters } from "vuex"; // 引入mapGetters,將Vuex的getter映射為computed變數
import { FETCH_EMPLOYEES } from "@/store/actions.type"; // 引入Vuex的動作(action)名稱
export default {
// 組件名稱
name: "Employee",
// 來自Vuex的computed屬性
computed: {
...mapGetters("employee", ["currentPage", "pageSize"])
}, // 從employee模組中使用Vuex getter,取得計算值(currentPage, pageSize)
methods: {
refreshList() {
store.dispatch(`employee/${FETCH_EMPLOYEES}`, {
page: this.currentPage,
page_size: this.pageSize
}); // 呼叫employee模組內的FETCH_EMPLOYEES動作(action),並帶入目前分頁資訊
}
}
};
</script>
詳細地說,資料會先透過Vuex的動作(action)觸發後端請求,取得後再由mutation存入、更新Vuex的狀態(state)。而基於Vue的響應式框架,當狀態(state)更新後,任何綁定該資料的元件都會自動重新渲染,無需手動改畫面。因此各組件讀取Vuex中的狀態(state)後,即可自動達成畫面的更新。
這即是Vuex的經典單向資料流(data flow)
Vue組件 → dispatch(呼叫action) → 發送API請求 → commit多個mutation → 更新Vuex狀態(state) → 畫面根據響應式狀態(getters)自動更新