count:6
}
// 定义 getters
var getters={
count(state){
return state.count
}
}
// 定义 actions ,要执行的动作,如流程的判断、异步请求
const actions ={
// ({commit,state}) 这种写法是 es6 中的对象解构
increment({commit,state}){
//提交一个名为 increment 的变化,名字可自定义,可以认为是类型名,与下方 mutations 中的 increment 对应
//commit 提交变化,修改数据的唯一方式就是显式的提交 mutations
commit('increment')
}
}
// 定义 mutations ,处理状态(数据) 的改变
const mutations ={
//与上方 commit 中的 ‘increment' 相对应
increment(state){
state.count ++;
}
}
// 创建 store 对象
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
// 导出 store 对象
export default store;
⑤ 在 app.vue 中引入 mapActions ,并调用
mapActions 用来获取方法(动作)
import {mapGetters,mapActions} from 'vuex'调用 mapActions 辅助方法,并传入一个数组,在数组中指定要获取的方法 increment
<template>
<div id="app">
//这个 increment 方法与下面 methods 中的 increment 相对应
<button @click="increment">增加</button>
<button>减少</button>
<h1>{{count}}</h1>
</div>
</template><script>
import {mapGetters,mapActions} from 'vuex'
export default {
name: 'app',
computed:mapGetters([
'count'
]),
methods:mapActions([
//该 increment 来自 store.js 中导出的 actions 和 mutations 中的 increment
'increment',
])
}
</script>
这样就能通过 button 来改变获取到的 count 了。
看起来确实是挺绕的,需要在理解了原理的情况下,再细细琢磨,加深理解。










