公用的数据都写在这里面
const state={
count:1
}
在组件中获取使用时可以通过三种方式
组件中引入辅助函数(当然先引入store.js,下面引入就不提了)
import { mapState } from 'vuex'
第一种
通过计算属性
computed: {
count () {
return this.$store.state.count
}
}
在模板中直接使用 {{count}} 就可以了
第二种
这就用到了辅助函数mapState ,同样需要计算属性
computed:mapState({
count:state=>state.count
})
模板中使用方法同上
第三种
其实为辅助函数简写的方法
computed:mapState(['count']),
当有多个函数时可以按下面这样写,用到了扩展运算符样式为(…)为es6方法可以把对象展开
computed:{
...mapState(['count']),
***,
***
},
模板中使用方法同上
store.js文件中创建Mutations 常量
const mutations={
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
模板中的使用
<p>
<button @click="$store.commit('add')">+button>
<button @click="$store.commit('reduce')">-button>
p>
上篇已经提到了这里就不做多提,这里主要提下简写方式,以及传送参数
由于是方法所以在methods中引入辅助函数
组件中引入
import { mapMutations} from 'vuex';
methods:{
...mapMutations(['add','reduce']),
}
模板中使用
<button class="btn" @click="add">+button>
<button class="btn" @click="reduce">-button>
传参数
const mutations={
add(state,n){
state.count++;
},
reduce(state,n){
state.count--;
}
}
两个参数第一个为state,第二个才是为传递的参数
组件模板中
//非简写
//简写
相当于一个过滤器,在store.js中加入getter常量
const getters = {
count:function(state){
return state.count +=100;
}
};
组件模板中引入辅助函数mapGetters并在计算属性
computed:{
...mapState(['count']),
...mapGetters(["count"])
},
这样每回修改都会加上100
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
创建action常量
const actions ={
addAction(context){
context.commit('add',10)
},
reduceAction({commit}){
commit('reduce')
}
}
context:上下文对象,这里你可以理解称store本身。
{commit}:直接把commit对象传递过来,可以让方法体逻辑和代码更清晰明了。
组件中引入
<button class="btn" @click="addAction">+button>
<button class="btn" @click="reduceAction">-button>
<script>
import {mapActions} from 'vuex';
methods:{
...mapActions(['addAction','reduceAction'])
}
script>