Vuex中的辅助函数
2022/9/1 23:25:33
本文主要是介绍Vuex中的辅助函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、组件访问state
- 从 vuex 中导入 mapState 函数
import { mapState } from 'vuex'
- 映射为当前组件的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
- 从vuex中导入mapMutations函数
import { mapMutations } from 'vuex'
- 将指定的 mapMutations 函数,映射为当前组件的methods方法
methods: { ...mapMutations(['add']) }
3.在methods使用
methods: { ...mapMutations(['add']), changeEvent(){ this.add(5); } }
三、触发actions
- 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'
- 在组件中添加代码
<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中的辅助函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist
- 2024-03-11icons for vue
- 2024-03-07breadcrumbs react js
- 2024-03-06react login page example
- 2024-03-06react router uselocation
- 2024-03-04postgres jsonb_set
- 2024-03-01react native uuid
- 2024-02-29vuejs sidebar