Vue之Vuex mapState 的使用

2022-04-01 16:26:05

mapState 是用来简化 computed 计算属性的一种写法,下面做一个对比:

  • 未使用之前
computed:{count(){returnthis.$store.state.count}},
  • 使用mapState之后
computed:{...Vuex.mapState(['count']),}

具体使用见下面代码详情


<!DOCTYPEhtml><htmllang="en"xmlns=""><head><metacharset="UTF-8"><title>Vuex:mapState 的使用</title></head><body><divid="app"><button-counter></button-counter></div><scriptsrc="vuex.js"></script><scriptsrc="vue.js"></script><script>
  Vue.component('ButtonCounter',{data(){return{
        localCount:5}},
    computed:{...Vuex.mapState([// 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以使用简写// 与 count: state => state.count 作用相同'count']),...Vuex.mapState({// 箭头函数可使代码更简练count:state=> state.count,// 传字符串参数 'count' 等同于 `state => state.count`
        countAlias:'count',// 为了能够使用 `this` 获取局部状态,必须使用常规函数countPlusLocalState(state){return state.count+this.localCount}})},
    methods:{...Vuex.mapMutations(['increment']),},
    template:`
      <div>
      <button @click="increment">You clicked me {{ count }} times.</button>
      <p>count: {{ count }}</p>
      <p>countAlias: {{ countAlias }}</p>
      <p>countPlusLocalState: {{ countPlusLocalState }}</p>
      </div>`})// 创建Vuex容器const store=newVuex.Store({
    strict:true,
    state:{
      count:0},
    mutations:{increment(state){
        state.count++}}})newVue({
    el:'#app',
    store});</script></body></html>

在这里插入图片描述

  • 作者:憶
  • 原文链接:https://blog.csdn.net/weixin_43094965/article/details/117636430
    更新时间:2022-04-01 16:26:05