欢迎访问我的博客地址 : 博客地址
router.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
num:0
}
const mutations = { //变更Store中的数据
add(state,step){ //累加step,若不加step,则可以直接定义好累加值
state.num += step
},sub(state,step){ //累减step
state.num -= step
},
//可以执行异步操作,但Mutation必须是同步函数,所以这种写法错误
// add(state,step){
// setTimeout(() => {
// state.num += step
// }, 1000);
// }
}
const actions = { //提交mutations,间接调用mutations,可执行异步操作
addActioins(state,step){
state.commit('add',step)
},
addAsync(state,step){
setTimeout(() => {
state.commit('add',step)
}, 1000);
},
subActions(state,step){
state.commit('sub',step)
},
subAsync(state,step){
setTimeout(() => {
state.commit('sub',step)
}, 1000);
}
}
const getters = { //getter对Store中已有的数据进行加工处理之后形成的数据,类似于vue中computed计算属性,起到包装作用
//getter中的数据跟随Store中的数据变化而变化
gettersNum(state){
return "当前num的值为:"+state.num
}
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
使用
<template>
<div>
<h1>
<!-- 方法一:state直接调用 -->
state1: 当前num的值为{{$store.state.num}} <hr>
<!-- 方法二:通过mapState函数映射出来 -->
state2:当前num的值为 {{num}} <hr>
<!-- 方法3:getters直接调用 -->
state3:{{this.$store.getters.gettersNum}} <hr>
<!-- 方法4:通过mapGetters计算属性直接映射 -->
state4:{{gettersNum}} <hr>
</h1>
<button @click='handleAdd'>add</button>
<button @click='handleSub'>sub</button> <hr>
<button @click='handleAddActions'>addActioins</button>
<button @click='handleAddAsync'>addAsync</button>
<button @click='addAsync(5)'>addAsync1</button>
</div>
</template>
<script>
import { mapState,mapMutations,mapActions,mapGetters } from 'vuex';
//引入所需函数
export default{
computed:{
...mapState(['num']),
// 将num 映射为this.$store.state.num, 使用对象展开运算符将此对象混入到外部对象中
...mapGetters(['gettersNum'])
// 将num 映射为this.$store.getters.gettersNum,
},methods:{
...mapMutations(['add','sub']),
//将add() 映射为this.$store.commit('add')
...mapActions(['addActioins','addAsync']),
//将addActioins() 映射为this.$store.dispatch('addActioins')
handleAdd(){
//1- 直接使用this.$store.commit()调用事件函数
// this.$store.commit('add',5)
//2- 使用mapMutations函数映射
this.add(5)
},handleSub(){
this.sub(5)
},handleAddActions(){
//1- 直接使用this.$store.dispatch()调用事件函数
this.$store.dispatch('addActioins',5)
//2- 使用mapMutations函数映射
// this.addActioins(5)
},handleAddAsync(){
this.addAsync(5)
}
}
}
</script>
<style lang='stylus' scoped>
div
padding 30px
</style>
</script>