整体的过程:
1、组件中通过this.$store.dispatch(‘increment’)调用action中的方法,
2、action通过commit()方法再调用mutation中的方法更新state中的数据,
3、最后state被修改后的数据重新显示的网页上。
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)//声明使用
//用于存储数据
const state = {
count: 0
}
//actions 用于响应组件上的动作
const actions = {
increment({ commit }) {
commit('INCREMENT')
},
decrement({ commit }) {
commit('DECREMENT')
},
incrementIfOdd({ commit, state }) {
if (state.count % 2 === 1) {
commit('INCREMENT')
}
},
incrementAsync({ commit }) {
setTimeout(() => {
commit('INCREMENT')
}, 1000)
}
}
//mutations 用于操作数据state
const mutations = {
INCREMENT(state) {
state.count += 1
},
DECREMENT(state) {
state.count -= 1
},
INCREMENTIFODD(state) {
state.count -= 1
},
INCREMENTASYNC(state) {
state.count -= 1
},
}
//包含多个getter计算属性的对象:相当于vue中的计算属性
const getters = {
eventOrOdd(state) {
return state.count % 2 === 0 ? "偶数" : "奇数";
}
}
//暴露
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
store //现在所有的组件对象都有属性:$store
})
App.vue
<template>
<div id="app">
<p>click {{ $store.state.count }} times, count is {{ eventOrOdd }}</p>//模板中不需要使用this.
<button @click="increment()">+</button>
<button @click="decrement()">-</button>
<button @click="incrementIfOdd()">increment if odd</button>
<button @click="incrementAsync()">increment async</button>
</div>
</template>
<script>
export default {
name: "App",
computed: {
eventOrOdd() {
return this.$store.getters.eventOrOdd;//这里需要使用this.
}
},
methods: {
increment() {
this.$store.dispatch('increment');
},
decrement() {
this.$store.dispatch('decrement');
},
incrementIfOdd() {
this.$store.dispatch('incrementIfOdd');
},
incrementAsync() {
this.$store.dispatch('incrementAsync');
}
}
};
</script>
<style></style>
======================================================================
改进
App.vue
<template>
<div id="app">
<p>click {{count }} times, count is {{ eventOrOdd }}</p>//count
<button @click="increment()">+</button>
<button @click="decrement()">-</button>
<button @click="incrementIfOdd()">increment if odd</button>
<button @click="incrementAsync()">increment async</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapActions} from 'vuex'//导入
export default {
name: "App",
computed: {
...mapState(['count']),//mapState()返回值是对象{count(){return this.$store.state['count']}}
...mapGetters(['evenOrOdd'])//mapGetters()返回值是对象{evenOrOdd () {return this.$store.getters.evenOrOdd}}
// click和store中的名字尽量写一致
//不一致时,使用对象写法...mapGetters({evenOrOdd:'evenOrOdd2'})
},
methods: {
...mapActions(['increment', 'decrement', 'incrementIfOdd', 'incrementAsync'])
},
components: {
FooterGuide
}
};
</script>
<style></style>
进一步使用可参考以下文章vuex进一步使用