Vuex中的辅助函数

2022/9/1 23:25:33

本文主要是介绍Vuex中的辅助函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

一、组件访问state
  1. 从 vuex 中导入 mapState 函数
import { mapState } from 'vuex'
  1. 映射为当前组件的computed计算属性:
...mapState(['count'])

3.添加到组件

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

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
    ...mapState(['count'])
  }
}
</script>
二、触发mutations
  1. 从vuex中导入mapMutations函数
import { mapMutations } from 'vuex'
  1. 将指定的 mapMutations 函数,映射为当前组件的methods方法
methods: {
    ...mapMutations(['add'])
}

3.在methods使用

methods: {
   ...mapMutations(['add']),
   changeEvent(){
    this.add(5);
   }
}
三、触发actions
  1. 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'
  1. 在组件中添加代码
<template>
  <div class="content">
    <div>当前最新count值:{{count}}</div>
    <div>getters: {{showNum}}</div>
    <button @click="changeEvent">触发按钮</button>
   </div>
</template>

<script>
import { mapState,mapActions} from 'vuex';
export default {
  name: 'Content',
  methods: {
    ...mapActions(['addAsync']),
    // 调用dispatch触发actions时携带参数
    changeEvent2() {
      this.addAsync(5);
    },
  },
  computed: {
    ...mapState(['count']),
  }
}
</script>
四、Getters
<template>
  <div class="content">
    <img alt="Vue logo" src="../assets/logo.png">
    <div>当前最新count值:{{count}}</div>
    <div>getters: {{showNum}}</div>
    <button @click="changeEvent1">触发同步按钮</button>
    <button @click="changeEvent2">触发异步按钮</button>
  </div>
</template>

<script>
import { mapState,mapMutations, mapActions, mapGetters} from 'vuex';
export default {
  name: 'Content',
  methods: {
    ...mapMutations(['add']),
    ...mapActions(['addAsync']),
    changeEvent1(){
     this.add(5);
    },
    // 调用dispatch触发actions时携带参数
    changeEvent2() {
      this.addAsync(5);
    },
  },
  computed: {
    ...mapState(['count']),
    ...mapGetters(['showNum'])
  }
}
</script>


这篇关于Vuex中的辅助函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程