vuex:弄懂mapState、mapGetters、mapMutations、mapActions
使用
<template>
<div class="home">
{{nickname}}
</div>
</template>
<script>
export default {
name: 'home',
computed:{
nickname(){
return this.$store.state.nickname
}
}
}
</script>
mapState(['nickname','age','gender']) //映射哪些字段就填入哪些字段
nickname(){return this.$store.state.nickname}
age(){return this.$store.state.age}
gender(){return this.$store.state.gender}
展开符
...mapState(['nickname','age','gender'])
getters相当于vue中的计算属性
getters:{
realname(state){
return state.firstname+state.lastname
},
money_us(state){
return (state.money/7).toFixed(2)
}
我们代码中定义的时候需要些mutations,它类似于vue中的methods
mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是state,第二个参数是载荷(payLoad),也就是额外的参数
mutations: { //类似于methods
addAge(state,payLoad){
state.age+=payLoad.number
}
}
mapMutations
跟mapState、mapGetters一样
methods:{
...mapMutations(['addAge'])
}
mapMutations(['addAge'])这一句就相当于下面的代码
addAge(payLoad){
this.$store.commit('addAge',payLoad)
}
参数我们可以在调用这个方法的时候写入
<button @click="addAge({number:5})">测试</button>
action类似于mutation
区别:action可以提交mutation
action也不要直接去操作state,而是去操作mutation
action包含异步操作,类似于axios请求,可以都放在action中写
action中的方法默认的就是异步,并且返回promise