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>