VUE学习(二十一)、Vuex(getters、mapState与mapGetters、mapMutations与mapActions、多组件共享数据、模块化编码)

一、Vuex普通实现求和案例

演示

实现

1、引入Vuex(store文件下index.js)

//该文件用于创建Vuex中最为核心的store
import Vue from "vue";
/* 此处不写在App.vue中的原因是因为应该先Vue.use(Vuex)再创建store实列对象但是es6规定import语句先执行,如果写在App.vue中则会出现先创建store实列对象再Vue.use(Vuex)的情况
*/
//引入Vuex
import Vuex from "vuex";
//应用Vuex插件
Vue.use(Vuex);
/*  操作数据前需要进行业务逻辑处理则写在actions中,如果仅仅直接修改数据就没必要写在actions中,直接调用mutations就行
*/
//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context, value) {console.log("actions中的jiaOdd被调用了");if (context.state.sum % 2) {context.commit("JIA", value);}},jiaWait(context, value) {console.log("actions中的jiaWait被调用了");setTimeout(() => {context.commit("JIA", value);}, 500);}
};
/*  mutations注重于操作数据,如果操作数据前有一定的业务逻辑则写在actions中
*/
//准备mutations——用于操作数据(state)
const mutations = {JIA(state, value) {console.log("mutations中的JIA被调用了");state.sum += value;},JIAN(state, value) {console.log("mutations中的JIAN被调用了");state.sum -= value;}
};
//准备state——用于存储数据
const state = {sum: 0 //当前的和
};//创建并暴露store
export default new Vuex.Store({actions,mutations,state
});

2、Count.vue组件

<template><div><h1>当前求和为:{{ $store.state.sum }}</h1><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment">+</button><button @click="decrement">-</button><button @click="incrementOdd">当前求和为奇数再加</button><button @click="incrementWait">等一等再加</button></div>
</template><script>
export default {name: "Count",data() {return {n: 1 //用户选择的数字};},methods: {increment() {this.$store.commit("JIA", this.n);},decrement() {this.$store.commit("JIAN", this.n);},incrementOdd() {this.$store.dispatch("jiaOdd", this.n);},incrementWait() {this.$store.dispatch("jiaWait", this.n);}},mounted() {console.log("Count", this);}
};
</script><style lang="css">
button {margin-left: 5px;
}
* {margin-left: 30px;
}
</style>

3、main.js(下同)

//引入Vue
import Vue from "vue";
//引入App
import App from "./App.vue";//引入store
import store from "./store";//关闭Vue的生产提示
Vue.config.productionTip = false;//创建vm
new Vue({el: "#app",render: (h) => h(App),store, // store配置项beforeCreate() {Vue.prototype.$bus = this;}
});

4、App.vue(下同)

<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},mounted() {// console.log('App',this)},}
</script>

二、Vuex中的getters

1、store下的indx.js中加入如下配置

/*  适用于想要复用这些逻辑并且只针对state操作
*/
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state) {return state.sum * 10;}
};

2、使用

<h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3>

三、mapState和mapGetters

1、store文件夹下的index.js

//该文件用于创建Vuex中最为核心的store
import Vue from "vue";
//引入Vuex
import Vuex from "vuex";
//应用Vuex插件
Vue.use(Vuex);//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context, value) {console.log("actions中的jiaOdd被调用了");if (context.state.sum % 2) {context.commit("JIA", value);}},jiaWait(context, value) {console.log("actions中的jiaWait被调用了");setTimeout(() => {context.commit("JIA", value);}, 500);}
};
//准备mutations——用于操作数据(state)
const mutations = {JIA(state, value) {console.log("mutations中的JIA被调用了");state.sum += value;},JIAN(state, value) {console.log("mutations中的JIAN被调用了");state.sum -= value;}
};
//准备state——用于存储数据
const state = {sum: 0, //当前的和school: "xxx大学",subject: "前端"
};
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state) {return state.sum * 10;}
};//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
});

2、Count.vue组件

<template><div><h1>当前求和为:{{ sum }}</h1><h3>当前求和放大10倍为:{{ bigSum }}</h3><h3>我在{{ school }},学习{{ subject }}</h3><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment">+</button><button @click="decrement">-</button><button @click="incrementOdd">当前求和为奇数再加</button><button @click="incrementWait">等一等再加</button></div>
</template><script>
import { mapState, mapGetters } from "vuex";
export default {name: "Count",data() {return {n: 1 //用户选择的数字};},computed: {//靠程序员自己亲自去写计算属性(等同于...mapState(["sum", "school", "subject"]))/* sum(){return this.$store.state.sum},school(){return this.$store.state.school},subject(){return this.$store.state.subject}, *///借助mapState生成计算属性,从state中读取数据。(对象写法)// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),//借助mapState生成计算属性,从state中读取数据。(数组写法)/*  ...的写法是因为mapState是一个对象,计算属性也是一个对象,不能在一个对象里直接写一个对象,所以用 ... 将对象展开放入计算属性中*/...mapState(["sum", "school", "subject"]),/* ******************************************************************** *//* bigSum(){return this.$store.getters.bigSum}, */// 借助mapGetters生成计算属性,从getters中读取数据。(对象写法)// ...mapGetters({bigSum:'bigSum'})//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(["bigSum"])},methods: {increment() {this.$store.commit("JIA", this.n);},decrement() {this.$store.commit("JIAN", this.n);},incrementOdd() {this.$store.dispatch("jiaOdd", this.n);},incrementWait() {this.$store.dispatch("jiaWait", this.n);}},mounted() {const x = mapState({ he: "sum", xuexiao: "school", xueke: "subject" });console.log(x);}
};
</script><style lang="css">
button {margin-left: 5px;
}
</style>

四、mapMutations和mapActions

1、store文件夹下index.js

//该文件用于创建Vuex中最为核心的store
import Vue from "vue";
//引入Vuex
import Vuex from "vuex";
//应用Vuex插件
Vue.use(Vuex);//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context, value) {console.log("actions中的jiaOdd被调用了");if (context.state.sum % 2) {context.commit("JIA", value);}},jiaWait(context, value) {console.log("actions中的jiaWait被调用了");setTimeout(() => {context.commit("JIA", value);}, 500);}
};
//准备mutations——用于操作数据(state)
const mutations = {JIA(state, value) {console.log("mutations中的JIA被调用了");state.sum += value;},JIAN(state, value) {console.log("mutations中的JIAN被调用了");state.sum -= value;}
};
//准备state——用于存储数据
const state = {sum: 0, //当前的和school: "xxx大学",subject: "前端"
};
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state) {return state.sum * 10;}
};//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
});

2、Count.vue组件

<template><div><h1>当前求和为:{{ sum }}</h1><h3>当前求和放大10倍为:{{ bigSum }}</h3><h3>我在{{ school }},学习{{ subject }}</h3><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment(n)">+</button><button @click="decrement(n)">-</button><button @click="incrementOdd(n)">当前求和为奇数再加</button><button @click="incrementWait(n)">等一等再加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {name: "Count",data() {return {n: 1 //用户选择的数字};},computed: {//借助mapState生成计算属性,从state中读取数据。(对象写法)// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(["sum", "school", "subject"]),/* ******************************************************************** *///借助mapGetters生成计算属性,从getters中读取数据。(对象写法)// ...mapGetters({bigSum:'bigSum'})//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(["bigSum"])},methods: {//程序员亲自写方法/* increment(){this.$store.commit('JIA',this.n)},decrement(){this.$store.commit('JIAN',this.n)}, *///借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations({ increment: "JIA", decrement: "JIAN" }),//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)// ...mapMutations(['JIA','JIAN']),/* ************************************************* *///程序员亲自写方法/* incrementOdd(){this.$store.dispatch('jiaOdd',this.n)},incrementWait(){this.$store.dispatch('jiaWait',this.n)}, *///借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" })//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)// ...mapActions(['jiaOdd','jiaWait'])},mounted() {const x = mapState({ he: "sum", xuexiao: "school", xueke: "subject" });console.log(x);}
};
</script><style lang="css">
button {margin-left: 5px;
}
</style>

五、Vuex实现多组件通信

1、store文件夹下的index.js

//该文件用于创建Vuex中最为核心的store
import Vue from "vue";
//引入Vuex
import Vuex from "vuex";
//应用Vuex插件
Vue.use(Vuex);//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context, value) {console.log("actions中的jiaOdd被调用了");if (context.state.sum % 2) {context.commit("JIA", value);}},jiaWait(context, value) {console.log("actions中的jiaWait被调用了");setTimeout(() => {context.commit("JIA", value);}, 500);}
};
//准备mutations——用于操作数据(state)
const mutations = {JIA(state, value) {console.log("mutations中的JIA被调用了");state.sum += value;},JIAN(state, value) {console.log("mutations中的JIAN被调用了");state.sum -= value;},ADD_PERSON(state, value) {console.log("mutations中的ADD_PERSON被调用了");state.personList.unshift(value);}
};
//准备state——用于存储数据
const state = {sum: 0, //当前的和school: "xxx大学",subject: "前端",personList: [{ id: "001", name: "张三" }]
};
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state) {return state.sum * 10;}
};//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
});

2、Count.vue插件

<template><div><h1>当前求和为:{{ sum }}</h1><h3>当前求和放大10倍为:{{ bigSum }}</h3><h3>我在{{ school }},学习{{ subject }}</h3><h3 style="color:red">Person组件的总人数是:{{ personList.length }}</h3><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment(n)">+</button><button @click="decrement(n)">-</button><button @click="incrementOdd(n)">当前求和为奇数再加</button><button @click="incrementWait(n)">等一等再加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {name: "Count",data() {return {n: 1 //用户选择的数字};},computed: {//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(["sum", "school", "subject", "personList"]),//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(["bigSum"])},methods: {//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations({ increment: "JIA", decrement: "JIAN" }),//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" })},mounted() {// const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})// console.log(x)}
};
</script><style lang="css">
button {margin-left: 5px;
}
</style>

3、Person.vue插件

<template><div><h1>人员列表</h1><h3 style="color:red">Count组件求和为:{{ sum }}</h3><input type="text" placeholder="请输入名字" v-model="name" /><button @click="add">添加</button><ul><li v-for="p in personList" :key="p.id">{{ p.name }}</li></ul></div>
</template><script>
import { nanoid } from "nanoid";
export default {name: "Person",data() {return {name: ""};},computed: {personList() {return this.$store.state.personList;},sum() {return this.$store.state.sum;}},methods: {add() {const personObj = { id: nanoid(), name: this.name };this.$store.commit("ADD_PERSON", personObj);this.name = "";}}
};
</script>

六、Vuex模块化编码


count.js和person.js在数据少,数据简单的时候也可以写在index.js中

1、store文件夹下index.js

//该文件用于创建Vuex中最为核心的store
import Vue from "vue";
//引入Vuex
import Vuex from "vuex";
import countOptions from "./count";
import personOptions from "./person";
//应用Vuex插件
Vue.use(Vuex);//创建并暴露store
export default new Vuex.Store({modules: {countAbout: countOptions,personAbout: personOptions}
});

2、store文件夹下count.js

//求和相关的配置
export default {namespaced: true,actions: {jiaOdd(context, value) {console.log("actions中的jiaOdd被调用了");if (context.state.sum % 2) {context.commit("JIA", value);}},jiaWait(context, value) {console.log("actions中的jiaWait被调用了");setTimeout(() => {context.commit("JIA", value);}, 500);}},mutations: {JIA(state, value) {console.log("mutations中的JIA被调用了");state.sum += value;},JIAN(state, value) {console.log("mutations中的JIAN被调用了");state.sum -= value;}},state: {sum: 0, //当前的和school: "xxx大学",subject: "前端"},getters: {bigSum(state) {return state.sum * 10;}}
};

3、store文件夹下person.js

//人员管理相关的配置
import axios from "axios";
import { nanoid } from "nanoid";
export default {namespaced: true,actions: {addPersonWang(context, value) {if (value.name.indexOf("王") === 0) {context.commit("ADD_PERSON", value);} else {alert("添加的人必须姓王!");}},addPersonServer(context) {axios.get("https://api.uixsj.cn/hitokoto/get?type=social").then((response) => {context.commit("ADD_PERSON", { id: nanoid(), name: response.data });},(error) => {alert(error.message);});}},mutations: {ADD_PERSON(state, value) {console.log("mutations中的ADD_PERSON被调用了");state.personList.unshift(value);}},state: {personList: [{ id: "001", name: "张三" }]},getters: {firstPersonName(state) {return state.personList[0].name;}}
};

4、Count.vue组件

<template><div><h1>当前求和为:{{ sum }}</h1><h3>当前求和放大10倍为:{{ bigSum }}</h3><h3>我在{{ school }},学习{{ subject }}</h3><h3 style="color:red">Person组件的总人数是:{{ personList.length }}</h3><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment(n)">+</button><button @click="decrement(n)">-</button><button @click="incrementOdd(n)">当前求和为奇数再加</button><button @click="incrementWait(n)">等一等再加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {name: "Count",data() {return {n: 1 //用户选择的数字};},computed: {//借助mapState生成计算属性,从state中读取数据。(数组写法)// ...mapState(["countAbout","personAbout"]) //(使用:countAbout.sum,countAbout.school······)...mapState("countAbout", ["sum", "school", "subject"]), //这种写法的前提是开启命名空间namespaced:true,(直接使用:sum,school·····)...mapState("personAbout", ["personList"]),//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters("countAbout", ["bigSum"])},methods: {//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations("countAbout", { increment: "JIA", decrement: "JIAN" }),//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions("countAbout", { incrementOdd: "jiaOdd", incrementWait: "jiaWait" })},mounted() {console.log(this.$store);}
};
</script><style lang="css">
button {margin-left: 5px;
}
</style>

5、Person.vue组件

<template><div><h1>人员列表</h1><h3 style="color:red">Count组件求和为:{{ sum }}</h3><h3>列表中第一个人的名字是:{{ firstPersonName }}</h3><input type="text" placeholder="请输入名字" v-model="name" /><button @click="add">添加</button><button @click="addWang">添加一个姓王的人</button><button @click="addPersonServer">添加一个人,名字随机</button><ul><li v-for="p in personList" :key="p.id">{{ p.name }}</li></ul></div>
</template><script>
import { nanoid } from "nanoid";
export default {name: "Person",data() {return {name: ""};},computed: {personList() {return this.$store.state.personAbout.personList;},sum() {return this.$store.state.countAbout.sum;},firstPersonName() {return this.$store.getters["personAbout/firstPersonName"];}},methods: {add() {const personObj = { id: nanoid(), name: this.name };this.$store.commit("personAbout/ADD_PERSON", personObj);this.name = "";},addWang() {const personObj = { id: nanoid(), name: this.name };this.$store.dispatch("personAbout/addPersonWang", personObj);this.name = "";},addPersonServer() {this.$store.dispatch("personAbout/addPersonServer");}}
};
</script>

VUE学习(二十一)、Vuex(getters、mapState与mapGetters、mapMutations与mapActions、多组件共享数据、模块化编码)相关推荐

  1. Vue学习笔记(十一)

    1.Vue学习笔记(十一) 文章目录 1.Vue学习笔记(十一) 1.1Vue_配置代理_方式 1.1.0演示问题 1.1.1运行node server1 1.1.2运行node server2 1. ...

  2. VUE学习(二十)、插槽

    VUE学习(二十).插槽 一.默认插槽 1.Category.vue <template><div class="category"><h3>{ ...

  3. OpenCV学习(二十一) :计算图像连通分量:connectedComponents(),connectedComponentsWithStats()

    OpenCV学习(二十一) :计算图像连通分量:connectedComponents(),connectedComponentsWithStats() 1.connectedComponents() ...

  4. vue外卖二十一:商家详情-评价列表-条件过滤显示评价:只显示好评/差评+显示只带内容评价、用getters生成好评数量新状态

    一.基本数据标识设计shop/ratings/ratings.vue 1)data数据设计 data(){return{showText:true, //条件1:只显示带文字的评价ratingType ...

  5. WEB前端 vue学习二 组件之间的数据传递

    Vue 的组件作用域都是孤立的,不允许在子组件的模板内直接引用父组件的数据.必须使用特定的方法才能实现组件之间的数据传递. 首先用 vue-cli 创建一个项目,其中 App.vue 是父组件,com ...

  6. Vue学习(二)-胡子({{}})语法

    一,插值操作 这种语法叫做 Mustache 语法 中文叫做胡子的意思,两个 {{}} 长的比较像胡子,所以这样命名了 <body><div id="app"&g ...

  7. android学习(二十一) 下载数据减少电池损耗

    高效的网络访问(优化下载) 使用无线网络下载数据是你的应用消耗电池潜在的重要原因之一.为了降低和网络有关的activity连接导致的电池消耗.你理解你的连接模型怎样影响无线硬件这是很关键的. 下面将介 ...

  8. Vuex实践-mapState和mapGetters

    一.前言 本文章是vuex系列的最后一篇,主要总结的是如何使用mapState和mapGetters访问vuex中的state和getters. 二.多个模块中mapState和mapGetters的 ...

  9. Vue3 直接使用Vuex的mapState和mapGetters时报错的分析及解决方案

    Vuex 提供了 mapState.mapGetters.mapActions 和 mapMutations 四个函数,其返回结果分别是 mappedState,mappedGetter,mapped ...

最新文章

  1. php分页不跳转,分页源代码,分页时上一页下一页不显示,但可以跳转
  2. 毕业设计之路(2)——初识TCP
  3. nagios nrpe
  4. 悲痛!高校一研究生在校内被撞身亡,肇事者为该校博导,警方已介入
  5. java 刽子手游戏_java基础(九):容器
  6. 怎么用计算机弹柯南,柯迷们的骚操作有哪些?用计算器弹柯南主题曲,自制缩小药丸...
  7. python pymysql使用连接池连接mysql示例
  8. MyBatis传入参数为0时条件不生效
  9. NYOJ--891--找点
  10. python中 是什么运算_“是”运算符在Python中做了什么?
  11. git小乌龟安装_ROS系统安装与体验
  12. swf文件的反编译入门
  13. JAVA中无法加载主类什么意思_找不到或无法加载主类什么意思?
  14. 后缀学习第三课(下)
  15. 计算机类专业都有什么区别?
  16. Linux(Centos7.8)中conda虚拟环境搭建LSTM神经网络基于django3.1.2的api接口
  17. 微信社群怎么做?-螳螂SCRM系统社群营销轻松裂变
  18. 硕士毕业论文模板(专业硕士)
  19. php仿阿里巴巴,php实现的仿阿里巴巴实现同类产品翻页
  20. 爬虫爬取糗事百科图片数据

热门文章

  1. 《Photoshop Lightroom5经典教程》—第1课复习题
  2. 从头学习爬虫(四十六)高阶篇----selenium获取network
  3. 创建FTP用户(简单版)
  4. 2000元左右有哪些性价比高的手机?不如看看荣耀
  5. 抖音无人直播项目技术丨三大玩法你知道吗?
  6. firework修改图片的颜色
  7. 业内人脸识别的主流科技公司
  8. Redis面试题汇总
  9. URL编码和解码 C++类URL编码和解码使用技巧
  10. 高通骁龙800/801/805/808/810/820/821/处理器参数对比介绍