vuex中mapState、mapMutations的用法

<template>
  <div>
    <!--vuex中的各种使用方法 mapState、mapMutations-->
    <a href="https://www.jb51.net/article/138239.htm">参考文档:getters,map等用法</a><br>
    <button @click="add(123456)">加</button>
    <!--<h3>count2:  {{count2}}</h3>-->
    <h4>roleAuthor:   {{roleAuthor}}</h4>
    <!--<h3>countAlias:{{countAlias}}</h3>-->
    <!--<h3>countPlusLocalState:{{countPlusLocalState}}</h3>-->
    <h3>test:{{test}}</h3>
    <hr>
    <h3>count:{{count}}</h3>
  </div>
</template>

<script>
  import {mapState,mapMutations} from 'vuex'
    export default {
        name: 'Storetest',
        data:function () {
            return{
              localCount:'6666666'
            }
        },
      /*----正常写法------*/
//      methods:{
//        add(){
//          this.$store.commit('add');
//        }
//      },

      /*---使用mapMutations--代替 $store.commit()- 传参的时候直接在行内写参数就可以了-*/
      methods:{
        ...mapMutations([
          'add'
        ])
      },

      /*----正常写法--------------*/
//      computed:{  //正常写法
//        count2(){
//          return this.$store.state.count;
//        }
//      }

      /*-------使用mapState辅助函数- 简洁的写法获取多个状态变量--------------*/
//      computed:mapState({
//        count2:state=>state.count, //理解为传入state对象,修改state.count属性
//        roleAuthor:state=>state.roleAuthor,
//        // 传字符串参数 'count' 等同于 `state => state.count`
//        countAlias: 'count',
//        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
//        countPlusLocalState (state) {
//          return state.count + this.localCount
//        }
//      })

      /*----计算属性名字和state的子节点名字相同时,可以直接传一个字符串数组*/
//      computed:mapState([
//        // 映射 this.count 为 store.state.count
//        'count',
//        'roleAuthor'
//      ])

      /*----使用对象展开运算符将此对象混入到外部对象中---------------*/
      computed:{
        ...mapState([
          // ...
          'count',
          'roleAuthor'
        ]),
        test(){
          return 'test'
        }
      }
    }
</script>

<style scope>

</style>

store.js

export default new Vuex.Store({
  state:{
    roleAuthor:'111111111111',
    count:0
  },

  mutations:{
    add(state,num){
      state.count =num;
    }
  },
  })
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值