vuex 四个map
vuex 四个map
mapState与mapGetter —多组件数据共享
位与computed内
mapState映射状态(数据) – 用计算属性映射共享数据state数据
简化
[this.]$store.state.variableName
main.js
中
// 2.创建store实例
const store = createStore({
state(){
return{
sum:0,
school:"尚硅谷",
subject:"前端"
}
},
actions:{
increment(context,value){
context.commit('INCREMENT', value)
}
},
mutations:{
INCREMENT(state,value){
state.sum+=value;
},
DECREMENT(state,value){
state.sum-=value;
},
INCREMENTODD(state,value){
state.sum+=value;
},
},
getters:{
bigSum(state){
return state.sum*10;
}
}
})
在模板中{
{ $store.state.variableName }}
太长了
<template>
<div>
<h1>当前求和为:{
{ $store.state.sum }}</h1>
<h2>当前求和扩大十倍后为:{
{ $store.getters.bigSum }}</h2>
<h3>我在{
{ $store.state.school }},学习{
{ $store.state.subject }}</h3>
</div>
</template>
用计算属性, 但是重复代码太多了
computed: {
sum() {
return this.$store.state.sum;
},
bigSum() {
return this.$store.getters.bigSum;
},
},
<template>
<div>
<h1>当前求和为:{
{ sum }}</h1>
<h2>当前求和扩大十倍后为:{
{ $store.getters.bigSum }}</h2>
</div>
</template>
mapState使用1 – 对象写法
//1.引入
import {
mapState } from "vuex";
//2.使用, 用mapstate生成计算属性,从state中读取数据
computed: {
// sum() {
// return this.$store.state.sum;
// },
// 来自getters不能用mapState
// bigSum() {
// return this.$store.getters.bigSum;
// },
//映射数据
...mapState({
sum: "sum", school: "school", subject: "subject" }),
},
mapState使用2 – 数组写法√
将使用1的对象写法改成数组写法, 原因是计算属性名和共享数据state名相同
...mapState([ "sum", "school", "subject" ]),
mapGetters映射 加工后的数据(Getters)
computed: {
// bigSum() {
// return this.$store.getters.bigSum;
// },
//对象写法
...mapGetters({
bigSum: "bigSum" }),
//数组写法 -- 计算属性和读取数据名相同
// ...mapGetters(["bigSum"]),
},
mapMutations与mapActions位与methods内
mapMutations 事件回调函数要记得传参
借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
对象写法
用于methods和Mutations方法名不同
1.模板
内事件回调要传参(参数是本组件的数据)
2.引入vuex中的mapMutations
扫描二维码关注公众号,回复:
14223466 查看本文章

<template>
<div>
<button @click="incrementOdd(本地数组参数)">当前求和为奇数再加</button>
<button @click="incrementWait(本地数组参数)">等等再加</button>
</div>
</template>
<script>
methods: {
...mapMutations({
incrementOdd: "INCREMENTODD", incrementWait: "INCREMENTWAIT",}),
}
</script>
数组写法 (回调函数与mutations内函数同名)
用于methods和Mutations方法名相同
回调函数名全部大写
<template>
<div>
<button @click="INCREMENTODD(本地数组参数)">当前求和为奇数再加</button>
<button @click="INCREMENTWAIT(本地数组参数)">等等再加</button>
</div>
</template>
<script>
methods: {
...mapMutations([ "INCREMENTODD", "INCREMENTWAIT"]),
}
</script>
mapActions
mapMutations 事件回调函数要记得传参
借助mapActions生成对应的方法,方法中会调用dispatch去联系actions
methods: {
//对象写法
//...mapActions({ increment: "increment", decrement: "decrement" }),
//数组写法(回调函数与actions内函数同名)
...mapActions(["increment", "decrement"]),
}
四个map总结