153-Vue中的vuex内的辅助函数——mapState,mapGetters,mapMutations,mapActions的用法

153-Vue中的vuex内的辅助函数——mapState,mapGetters,mapMutations,mapActions的用法

首先查看目录:

 

此文章所涉及到的代码:src/components/Comp1.vue

store/index.js

views/HomeView.vue

其它的都是初建的代码,未做改动,此处不展示。

Comp1.vue代码如下:

<template>
<!-- Vuex辅助函数写法 -->
    <div>
        <p>{{num}}</p>
        <p>{{title}}</p>
        <p>{{dbNum}}</p>
        <button @click="chanNum(1)">同步按钮</button>
        <!-- <button @click="add">同步按钮</button> -->
        <button @click="asyncChanNum(100)">异步按钮</button>
        <!-- <button @click="add1">异步按钮</button> -->
    </div>
</template>

<script>
import { mapMutations, mapState,mapActions,mapGetters } from 'vuex'
export default {
    methods:{
        ...mapMutations(['chanNum']), // 同步
        // add(){
        //     this.$store.commit('chanNum',10)
        // },
        ...mapActions(['asyncChanNum']), // 异步
        // add1(){
        //     this.$store.dispatch('asyncChanNum',100)
        // }
    },
    computed:{
        ...mapState(['num','title']),
        // num(){
        //     return this.$store.state.num
        // }
        ...mapGetters(['dbNum']),
        // dbNum(){
        //     return this.$store.getters.dbNum
        // }
    },
    data () {
        return {

 
        }
    }
}
</script>
 
<style lang = "less" scoped>
    
</style>

 store/index.js代码如下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    num:11,
    title:'标题'
  },
  getters: {
    dbNum(state){
      return state.num*2
    }
  },
  mutations: { // 同步
    chanNum(state,payload){
      state.num+=payload
    }
  },
  actions: { // 异步
    asyncChanNum({commit},payload){
      setTimeout(()=>{
        commit('chanNum',payload)
      },1000)
    }
  },
  modules: {
  }
})

views/HomeView.vue代码如下:

<template>
  <div class="home">
    <HelloWorld />
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/Comp1.vue'

export default {
  name: 'HomeView',
  components: {
    HelloWorld
  }
}
</script>

下面显示操作步骤:

最终效果如下:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值