Vuex中的輔助函數(shù)

上篇文章我們講了Vuex的使用,本來想把是想把Vuex內(nèi)容寫一塊,后來覺得那樣會(huì)太亂不利于入門的同學(xué)消化理解,Vuex的使用問題請(qǐng)看上篇,本篇只講輔助函數(shù)。

一、組件訪問state
  1. 從 vuex 中導(dǎo)入 mapState 函數(shù)
import { mapState } from 'vuex'
  1. 映射為當(dāng)前組件的computed計(jì)算屬性:
...mapState(['count'])

3.添加到組件

<template>
  <div>
    <h1>count值:{{count}}</h1>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
    ...mapState(['count'])
  }
}
</script>
二、觸發(fā)mutations
  1. 從vuex中導(dǎo)入mapMutations函數(shù)
import { mapMutations } from 'vuex'
  1. 將指定的 mapMutations 函數(shù),映射為當(dāng)前組件的methods方法
methods: {
    ...mapMutations(['add'])
}

3.在methods使用

methods: {
   ...mapMutations(['add']),
   changeEvent(){
    this.add(5);
   }
}
三、觸發(fā)actions
  1. 從 vuex 中按需導(dǎo)入 mapActions 函數(shù)
import { mapActions } from 'vuex'
  1. 在組件中添加代碼
<template>
  <div class="content">
    <div>當(dāng)前最新count值:{{count}}</div>
    <div>getters: {{showNum}}</div>
    <button @click="changeEvent">觸發(fā)按鈕</button>
   </div>
</template>

<script>
import { mapState,mapActions} from 'vuex';
export default {
  name: 'Content',
  methods: {
    ...mapActions(['addAsync']),
    // 調(diào)用dispatch觸發(fā)actions時(shí)攜帶參數(shù)
    changeEvent2() {
      this.addAsync(5);
    },
  },
  computed: {
    ...mapState(['count']),
  }
}
</script>
四、Getters
<template>
  <div class="content">
    <img alt="Vue logo" src="../assets/logo.png">
    <div>當(dāng)前最新count值:{{count}}</div>
    <div>getters: {{showNum}}</div>
    <button @click="changeEvent1">觸發(fā)同步按鈕</button>
    <button @click="changeEvent2">觸發(fā)異步按鈕</button>
  </div>
</template>

<script>
import { mapState,mapMutations, mapActions, mapGetters} from 'vuex';
export default {
  name: 'Content',
  methods: {
    ...mapMutations(['add']),
    ...mapActions(['addAsync']),
    changeEvent1(){
     this.add(5);
    },
    // 調(diào)用dispatch觸發(fā)actions時(shí)攜帶參數(shù)
    changeEvent2() {
      this.addAsync(5);
    },
  },
  computed: {
    ...mapState(['count']),
    ...mapGetters(['showNum'])
  }
}
</script>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容