<template>
<div id="app">vue
<p>click{{$store.state.count}} times, count is {{evenOrOdd}}</p> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="incrementIfOdd">increment if odd</button> <button @click="incrementAsync">increment if async</button>
</div>
</template>vuex
<script>
export default {
name: 'App',
data(){npm
return { }
},
computed:{
evenOrOdd(){app
return this.$store.getters.evenOrOdd
}
},
methods:{async
increment(){ // 通知Vuex去增長 this.$store.dispatch('increment') /* 觸發store中對應的action調用 */ }, decrement(){ this.$store.dispatch('decrement') }, // 若是是奇數才增長以 incrementIfOdd(){ this.$store.dispatch('incrementIfOdd') }, // 過1s才增長 incrementAsync(){ this.$store.dispatch('incrementAsync') },
}
}
</script>函數
<style>this
</style>spa
// Vuex的核心管理對象模塊
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//狀態對象
const state ={eslint
// 初始狀態 count: 0
}
//包含多個更新state函數的對象
const mutations ={
INCREMENT(state){
state.count++
},
DECREMENT(state) {code
state.count--
}
}
const actions = { //包含多個對應事件回調函數的對象
// 增長的action
increment({commit}) {
commit('INCREMENT')
},
// 減小的action
decrement({commit}) { commit('DECREMENT') }, incrementIfOdd({commit,state}) { // 不須要調用, 只須要讀取屬性值 if (state.count % 2 == 1) { commit('INCREMENT') } }, incrementAsync({commit}) { setTimeout(() => { commit('INCREMENT') }, 1000) },
}
//包含多個getter計算屬性的對象
const getters ={
evenOrOdd(state) {
return state.count % 2 == 0 ? '偶數' : '奇數';
},
}
export default new Vuex.Store({
state, //狀態對象 mutations, //包含多個更新state函數的對象 actions, //包含多個對應事件回調函數的對象 getters //包含多個getter計算屬性的對象
})
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
/ eslint-disable no-new /new Vue({ el: '#app', store, components: { App }, template: '<App/>'})