第一节我们初步见识了Mutations,这节我们再来详细看看,首先我们在store里面的mutations的方法加个参数
const mutations = {
add(state,n){
state.count+=n;
},
reduce(state){
state.count--;
}
}
然后是我们的Count.vue组件
<template>
<div>
<h1>{{ msg }}</h1>
<!--直接引用store里的数据-->
<h2>{{ $store.state.count }}--{{ count }}</h2>
<!--这里就可以用我们的methods-->
<button @click="add(10)">+</button>
<button @click="reduce">-</button>
</div>
</template>
<script>
import store from '@/vuex/store'
//这里多了个mapMutations
import { mapState,mapMutations } from 'vuex'
export default {
data(){
return {
msg: 'Hello Vuex!'
}
},
computed:mapState(['count']),
//将mutations添加到menthods里面
methods:mapMutations(['add','reduce']),
//将store添加到实例
store
}
</script>
<style>
</style>
提示:这里我们可以看看我们调用方法时和声明方法的参数是有区别的
add(state,n);//声明
add(10);//调用,state是不用传的
//按我们第一节调用的,也是不一样的
$store.commit('add',10);