1. vue create 中加上vuex
2. vue-cli脚手架生成后, main.js如下:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
3.store下的index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
mutations: {
//操作state数据
add(state){
state.count= state.count+1
},
addN(state,step){
state.count=state.count+step
}
,
sub(state){
state.count=state.count-1
}
,
subN(state,step){
state.count=state.count-step
}
},
actions: {
// 异步操作 不能直接操作 state 的数据
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
,
addAsyncN(context,step){
setTimeout(()=>{
context.commit('addN',5)
},1000)
}
,
subAsync(context){
setTimeout(()=>{
context.commit('sub')
},1000)
}
,
subNAsync(context,step){
setTimeout(()=>{
context.commit('subN',5)
},1000)
}
},
modules: {
}
,
getters:{
showNum(state){
return "目前的count值是:["+ state.count+"]"
}
}
})
4.Addition.vue
<template>
<div>
<h3>count的当前值为:{{ count }} </h3>
<button @click="handle1">+1</button>
<button @click="handle2">+5</button>
<button @click="handle3">+1 Async</button>
<button @click="handle4">+5 Async</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed:{
...mapState(["count"])
},
methods:{
handle1(){
// this.$store.state.count++
// 第一种方法
this.$store.commit('add')
console.log("hello world")
}
,
handle2(){
this.$store.commit("addN",5)
},
handle3(){
this.$store.dispatch("addAsync")
}
,
handle4(){
this.$store.dispatch("addAsyncN",5)
}
}
}
</script>
<style>
</style>
5.Substraction.vue
<template>
<div>
<!-- <h3>count的当前值为 : {{count}} </h3> -->
<h3>{{showNum}}</h3>
<button @click="handle1">-1</button>
<button @click="handle2">-3</button>
<button @click="subAsync">-1 async</button>
<button @click="subNAsync">-5 async</button>
</div>
</template>
<script>
import { mapState , mapMutations, mapActions ,mapGetters} from 'vuex'
export default {
computed:{
...mapState(['count']),
...mapGetters(['showNum'])
}
,
methods:{
...mapMutations(['sub','subN']),
...mapActions(['subAsync','subNAsync']),
handle1(){
this.sub()
console.log(" oh yes!!!");
}
,
handle2(){
this.subN(3)
}
}
}
</script>
<style></style>
5.相关操作
读取
第一种方法: this.$store.state.count;
第二种方法 import { mapState } from 'vuex'
在computed中 加入 ...mapState(['count']) ,自动映射到本组件的count
操作Mutations
第一种方法: this.$store.commit('add')
第二种方法: import { mapMutations } from 'vuex'
在method中 加入 ...mapMutations(['add']),自动映射到本组件的add()
操作Actions
第一种方法:this.$store.dispatch('sub')
第二种方法: import { mapActions } from 'vuex'
在 method中 加入 ...mapActions(['sub']),自动映射到被组件的sub()
注意:在actions中
subAsync(context){
setTimeout(()=>{
context.commit('sub')
},1000)
}