vuex的辅助函数,太好用了

辅助函数简化了获取store中的state、getters、mutations、actions,使用方法如下:
首先在组件中的script引入

//需要哪个引入哪个即可
import {
    
     mapState, mapGetters, mapMutations, mapActions } from 'vuex'

因为state和getters返回的是属性,也就是具体的值,所以mapState和mapGetters应该放在计算属性computed中。

//home.vue
<div>{
    
    {
    
     name }}{
    
    {
    
     getName }}</div>

computed:{
    
    
    ...mapState(['name']) // =>this.$store.state.name
    ...mapGetters(['getName']) // =>this.$store.getters.getName
}

因为mutations和actions返回的是函数,所以应该放在组件的methods属性中。

mounted(){
    
    
    this.setName(传参)
},
methods:{
    
    
    ...mapMutations(['setName'])
}

猜你喜欢

转载自blog.csdn.net/qq_44415875/article/details/127917476