<template>
<div>
<h2>{{msg}}</h2><hr/>
<h3>{{$store.state.count}}--{{count}}</h3>
<!-- 模块组 -->
<h3>{{count}}</h3>
<p>
<button @click="$store.commit('add')">+</button>
<button @click="reduce">-</button>
</p>
<p>
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store';
import { mapState,mapMutations,mapGetters, mapActions} from 'vuex';
export default {
store,
data(){
return{
msg:'hello Vuex'
}
},
//第一种
/*
computed:{
count(){
return this.$store.state.count
}
}
*/
//第二种
/*
computed:mapState({
count:state=>state.count,
})
*/
//第三种
computed:{
...mapState(['count']),
...mapGetters(['count']),
//模块组
count(){
return this.$store.state.a.count
},
},
methods:{
...mapMutations(['add','reduce']),
...mapActions(['addAction','reduceAction'])
},
}
</script>
//数据仓库
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//共享值就是状态
//mapState
const state={
count:1
}
//改变状态对象的方法
//Mutations
const mutations={
add(state,n){
state.count+=n;
},
reduce(state){
state.count--;
}
}
//mapGetters
//mapActions
const getters={
count:function(state){
return state.count+=100
}
//count:state=>state.count+=100,
}
//异步
const actions={
addAction(context){
context.commit('add',10);
setTimeout(() => {
context.commit('reduce')
}, 3000);
},
reduceAction({commit}){
commit('reduce');
}
}
//模块组 为了共同开发。
const moduleA={
state,
mutations,
getters,
actions
}
// const moduleB={
// state,
// mutations,
// getters,
// actions
// }
//暴露出去
export default new Vuex.Store({
modules:{a:moduleA,}
})