先来个极简版本的按钮计数器
如官网所述,状态更改方法写在store里
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store= new Vuex.Store({
state: {
count:0
},
mutations: {
increment(state){
state.count++
},
decrement(state){
state.count--
}
},
});
export default store
在页面上用$store.commit()去使用方法
<template>
<div>
<h1>我是组件</h1>
<button @click="$store.commit('increment')">+</button>
<span>{{$store.state.count}}</span>
<button @click="$store.commit('decrement')">-</button>
</div>
</template>
<script>
import store from '../store'
export default {
store,
name:"HelloWorld",
data(){
return{
count:0
}
},
}
效果图
升级版本
主要引用辅助函数,去简写标签里的方法
<template>
<div>
<h1>我是组件</h1>
<button @click="increment">+</button>
<span>{{count}}</span>
<button @click="decrement">-</button>
</div>
</template>
<script>
import store from '../store';
import {mapState, mapMutations} from 'vuex';
export default {
store,
name:"HelloWorld",
data(){
return{
// count:0
}
},
computed:
// 方法一 计算属性
// {
// count(){
// return this.$store.state.count
// }
// }
// 方法二 mapState 辅助函数
// mapState({
// count:function(state){
// return state.count
// }
// })
// 方法三 数组 照这么写 数组方法最简洁
mapState(['count']),
methods:mapMutations(['increment','decrement'])
}
</script>