Vue 的使用入門
- Vuex摘要
State: 管理應用的共享狀態。 Mutations: 唯一能夠修改 state 的方法,必須是同步的。 Actions: 用來執行異步操作,然後觸發 mutations。 Getters: 用來從 state 中派生出其他狀態,通常用來計算或過濾 state。
- #0 安裝 Vuex:termial
npm install vuex
- #1 創建一個 Vuex Store:store/index.js
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { count: 0, }, mutations: { increment(state) { state.count++; }, }, actions: { increment({ commit }) { commit('increment'); }, }, getters: { doubleCount(state) { return state.count * 2; }, }, });
- #2 在主 Vue 實例中使用 Vuex Store:main.js
import Vue from 'vue'; import App from './App.vue'; import store from './store'; new Vue({ store, render: h => h(App), }).$mount('#app');
- #3 從 Store 相關設置:computed 變更 count
computed: { count() { return this.$store.state.count; }, },
- 提交 mutation method
methods: { increment() { this.$store.commit('increment'); }, },
- 調用 action(function 用法)
methods: { increment() { this.$store.dispatch('increment'); }, },
- 使用 getters(獲取value)
computed: { doubleCount() { return this.$store.getters.doubleCount; }, },