2020年啦,复习一下Vuex,这样才能温故而知新,记下来
1:先安装下vuex
cnpm install vuex --save
2:新建一个vuex文件夹,下面新建一个store.js
3:store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state={
count:1
}
const mutations={
add(state){
state.count++
},
reduce(state){
state.count--
}
}
export default new Vuex.Store({
state,
mutations
})
4:新建一个Conter.vue,用来存放count
<template>
<div>
<h2>Vuex</h2>
<div>
<button @click=" $store.commit('reduce')">-</button>
<span>{{$store.state.count}}</span>
<button @click=" $store.commit('add')">+</button>
</div>
</div>
</template>
<script>
import store from '@/vuex/store';
export default{
name:'count',
data(){
return{
count:0
}
},
store,
methods:{
}
}
</script>
<style>
</style>
效果图
~基本的功能就实现啦
但是我们发现{{$store.state.count}}写法不太简洁,我们用三种方法来改写一下
第一种方法:计算属性
computed:{
count(){
return this.$store.state.count
}
}
第二种方法:mapState
import {mapState} from 'vuex';
computed:mapState({
count:state=>state.count
})
也可以不用用箭头函数改写一下咯
computed:mapState({
count:function(state){
return state.count
}
})
第三种方法:数组
computed:mapState(['count'])
大功告成
那么如何传递参数了?
具体是在mutations种传递参数
const mutations={
add(state,n){
state.count += n
},
reduce(state){
state.count--
}
}
使用
<button @click=" $store.commit('add',10)">+</button>
效果图
大功告成
我们想把提交方法简写,不要那么长,具体怎么实现了?
答案就是用mutations
1:引入mapMutations
import {mapState,mapMutations} from 'vuex';
2:方法改写
methods:mapMutations(['add','reduce']),
3:点击事件
<button @click=" reduce">-</button>
那么如果想在每次加之前过滤一下,比如+100,再执行后续的计算该如何实现了?
答案是getters
1:定义一个getters
const getters={
count:function(state){
return state.count += 100
}
}
接下来我们实现一下异步提交,好不好
1:先定义一个actions
const actions={
addAction(context){
context.commit('add',10);
setTimeout(()=>{
context.commit('reduce');
},5000)
console.log('我是异步哦...')
},
reduceAction({commit}){
commit('reduce');
}
}
2:重新定义一个点击方法
<div>
<button @click="reduceAction">-</button>
<span>{{$store.state.count}}---{{count}}</span>
<button @click="addAction">+</button>
</div>
3:使用
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex';
methods:{
...mapMutations(['add','reduce']),
...mapActions(['reduceAction','addAction'])
},