mapState 和mapGetters
- 用于生成计算属性computed
- mapState({“计算属性名”:“State数据”,“xxx”:“xxxx”,…}),返回的是一系列函数
- mapState([‘计算属性和State里数据同名’,“xxxx”,“xxx”,…])此处为简写形式
- mapGetters用法基本一致

-
通过mapState,mapGetters生成的数据为vuex bindings
-
import { mapState,mapGetters} from 'vuex' computed:{ s(){ return 500}, ...mapState({ sum1:"sum"}), ...mapState(["sum"]), ...mapGetters({ bigsum1:"bigsum"}), ...mapGetters(["bigsum"]) } ,

mapActions和mapMutations
-
mapMutations可以生成$store.commit
-
使用方法为…mapMutations({‘函数名’:‘Mutations里对应函数名字’})(对象形式写法)
-
…mapMutations([‘chu’])(数组形式写法)
-
使用时注意函数名要传参
-
借助mapMutation生成对应方法,方法中会调用commit去联系Mutations
-
mapActions和mapMutations用法基本相同
-
借助mapActions生成对应方法,方法中会调用dispatch去联系Actions
...mapMutations({'chu':'CHU'}) ====>>>>>> chu(){ this.$store.commit('CHU',this.number) } -
mapActions和mapMutations使用时,如果需要传递参数,要在模板中绑定事件是传递好参数,否则参数是事件对象

<template>
<div >
<div>{
{
sum}}</div>
<div>{
{
$store.getters.bigsum}}</div>
<select v-model.number="number">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="jia(number)">+++++++++</button>
<button @click="jian(number)">---------</button>
<button @click="cheng(number)">******</button>
<button @click="CHU(number)">//</button>
</div>
</template>
<script>
import {
mapState,mapGetters, mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
number:1
}
},
computed:{
s(){
return 500},
...mapState({
sum1:"sum"}),
...mapState(["sum"]),
...mapGetters({
bigsum1:"bigsum"}),
...mapGetters(["bigsum"])
}
,
methods:{
// add(){
// this.$store.dispatch('jia',this.number)
// },
// jian(){
// this.$store.dispatch("jian",this.number)
// },
// cheng(){
// this.$store.dispatch("cheng",this.number)
// },
...mapActions(['jia','jian','cheng']),
// CHU(){
// this.$store.commit('CHU',this.number)
// },
...mapMutations(['CHU'])
}
}
</script>
<style>
</style>
多组件数据共享
APP Components
<template>
<div >
<Count ref='ccc' />
<hello/>
</div>
</template>
<script>
import Count from "./components/Count.vue"
import hello from "./components/hello.vue"
export default {
name:"App",
components:{
Count,hello
},
mounted() {
this.$refs.ccc.$on("hello",()=>{
console.log("hello,word");
})
},
}
</script>
<style>
</style>
HELLO components

本文介绍了Vuex中的mapState、mapGetters、mapActions和mapMutations的用法,它们分别用于创建计算属性和绑定状态修改操作。在多组件数据共享中,Vuex的模块化提供了命名空间来管理不同部分的状态。通过使用这些映射函数,开发者能够更方便地在组件中访问和修改Vuex store中的数据。
最低0.47元/天 解锁文章
921

被折叠的 条评论
为什么被折叠?



