程式碼部分:
store:
export default new Vuex.Store({
state: {
accounts: []
},
mutations: {
fetchAccounts: (state, payload) => {
state.accounts = ["Edward", "Daisy"]
}
},
actions: {
fetchAccounts: ({ commit }) => {
commit("fetchAccounts")
}
},
})
ps.這邊我的個人習慣,會將actions的函式名稱與mutation相同。這樣在管理上面,容易區分出哪一個actions是用來執行哪一個mutation。
import { mapActions, mapState } from "vuex";
export default {
name: "Home",
components: {},
methods: {
...mapActions(["fetchAccounts"]),
},
computed: {
...mapState(["accounts"]),
},
};
元件或組件,透過methods去dispatch Store的Actions,並將回傳的結果傳回頁面上mapState,最後由computed運做出來。
使用時,僅需要引入在模板上即可:
<template>
<div class="home">
<button @click="fetchAccounts">Fetch Account</button>
<br />
<pre>結果顯示:{{ accounts }}</pre>
</div>
</template>