new Vue({ // state data () { return { count: 0 } }, // view template: ` <div>{{ count }}</div> `, // actions methods: { increment () { this.count++ } } })
├─src
│ ├─components
│ ├─router
│ ├─store (new)
│ │ └─index.js (必備預設檔名)
│ └─main.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = {} const getters = {} const actions = {} const mutations = {} export default new Vuex.Store({ state, getters, actions, mutations })
... import store from './store'; new Vue({ el: '#app', router, // 加入 store store, template: '<App/>', components: { App } })
腳色 | 職權 |
---|---|
state | 存放 APP 所有 state |
action | 調用 mutation 函式及處理 ajax (非同步) |
getter | 負責取 state 資料 |
mutation | 負責改變 state 資料 (同步) |
import { mapActions } from 'vuex' export default { // ... methods: { // 方法一 直接取用 ...mapActions([ 'increment' ]), // 方法二 另存別名取用 ...mapActions({ add: 'increment' // 使用 add 為元件內別名 }), // 方法三 直接呼叫使用 actionIncrement(){ this.$store.dispatch('increment') } } }
import { mapGetters } from 'vuex' export default { data () { return { // 方法三 直接呼叫使用 count: this.$store.state.count } }, computed: { // 方法一 直接取用 ...mapGetters([ 'getCount' ]), // 方法二 另存別名取用 ...mapGetters({ count: 'getCount' // 使用 add 為元件內別名 }) } }