template模板部分
<template>
<div>
<h1>当前最新的count值:{{count}}</h1>
<h1>{{showNum}}</h1>
<button @click="sub()">-</button>
<button @click="subN(3)">-N</button>
<button @click="subAsyncN(9)">-AsyncN</button>
</div>
</template>
js部分
<script>
import { mapState, mapMutations, action, mapActions, mapGetters } from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState(['count']),
...mapGetters(['showNum'])
},
methods: {
...mapMutations(['sub', 'subN']),
...mapActions(['subAsyncN'])
}
}
vuex核心story.js详细说明
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
// mutations用于变更store中的数据,mutation不能写异步代码
// 只有mutation 中定义的函数,才有权利修改state中的数据
mutations: {
add(state) {
state.count++
},
addN(state, step) {
state.count += step
},
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}
},
// action 用于处理异步任务
actions: {
addAsync(context) {
setTimeout(() => {
// 在action中不能直接修改state中的数据
// 必须通过 context.commit() 触发某个mutation 才可以
context.commit('add')
}, 1000)
},
addAsyncN(context, step) {
setTimeout(() => {
// 在action中不能直接修改state中的数据
// 必须通过 context.commit() 触发某个mutation 才可以
context.commit('addN', step)
}, 1000)
},
subAsyncN(context, step) {
setTimeout(() => {
// 在action中不能直接修改state中的数据
// 必须通过 context.commit() 触发某个mutation 才可以
context.commit('subN', step)
}, 1000)
}
},
getters: {
showNum(state) {
return '当前最新数量是【' + state.count + '】'
}
}
})