Vue学习笔记 —— Vuex之辅助函数

本文介绍了Vuex的mapState辅助函数,它帮助简化在Vue组件中获取多个state值的过程。在组件的computed属性中使用mapState,可以直接在模板中引用state,而无需通过$store.state。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mapState辅助函数

作用:可以辅助获取到多个state的值

import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex);

const state={
    count:0,
    num:100
}
const  getters={
    changeCount(){
        return state.count++
    }
}
const actions={
    acCountAdd({commit},val){
        commit('muCountAdd',val)
    }
}
const mutations={
    countAdd(state,val){
        state.count+=val
    }
}

export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations
})

使用

<template>
  <div>
    <h2>home</h2>
    <h3>vuex中的state的count:{{count}}</h3>
    <h3>vuex中的getters的changeState:{{changeCount}}</h3>
    <!-- 使用action辅助函数后,可以直接调用acCountAdd方法 -->
    <button @click='acCountAdd(10)'>home改变vuex</button>
  </div>
</template>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from "vuex"
export default {
  name: "Home",
  computed:{
    // 
    ...mapState({
      count: state=>state.count
    }),
    // 
    ...mapGetters({
      changeCount: 'changeCount'
    })
  },
  methods: {
  	//
      ...mapMutations({
      muCountAdd: 'muCountAdd'
    }),
    // 
    ...mapActions({
      acCountAdd: 'acCountAdd'
    })
  },
};
</script>
  1. 在.vue组件中引入

    import { mapState } from 'vuex'
    
  2. 在vue组件中定义一个对象

    computed:{
    	...mapState({
    		count: state => state.count
    	})	
    }
    
  3. 然后就可以不用$store.state.num引用了,直接插值

    {{count}}
    

    mapState需要写在computed中。
    mapGetters、mapMutations、mapActions需要写在methos中。

    import { mapGetters} from 'vuex'
    
    computed:{
    	...mapGetters({
    		changeCount: 'changeCount'
    	})	
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值