:::
14-8 使用vuex
- 先建立 store/index.js,如:
export const state = () => ({ counter: 0 }); export const actions = { handleAddCounter({ commit }) { commit("addCounter"); } }; export const mutations = { addCounter(state) { state.counter++; } }; export const getters = { getCounter: state => { return `counter: ${state.counter}`; } }; - store目錄內的每一個.js檔案都會被轉換為一個 namespaced module (index為根模組)。你的
state應該始終是一個函式,以避免在伺服器端出現不必要的共享狀態。 - 加入methods,以便觸發vuex actions中的方法,並加入 computed 以取得 getters 的值
methods: { handCounter() { this.$store.dispatch('handleAddCounter'); // console.log(this.$store.getters.getCounter); }, }, computed:{ getCount(){ return this.$store.getters.getCounter; } } - 樣板部份也加入按鈕並顯示之
<button @click="handCounter">按我計數+1 {{getCount}}</button> - 也可以從後端直接取得 state 的值
async asyncData({ app }) { return { counter: app.store.state.counter }; }, - 從後端也可以利用 dispatch 將值塞進 state 中,若要如此,就不要 return,而是在 computed 中用 getters 去取得 state 的值,不然會造成兩份資料可能會不一致的問題。
- 若要做成 Vuex module,只要在 store/ 下建立一個目錄即可,如 store/User/index.js
- 若要拆分 Vuex,只要分別存成 store/User/state.js、store/User/actions.js、store/User/mutations.js、store/User/getters.js 即可
14-7-4 將 localStorage 做成 plugin