【Vue】第十七部分 Vuex、多组件共享数据、四个map方法、namespace、Vuex模块化 (重要)

本文主要是介绍【Vue】第十七部分 Vuex、多组件共享数据、四个map方法、namespace、Vuex模块化 (重要),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Vue】第十七部分 Vuex、多组件共享数据、四个map方法、namespace、Vuex模块化 (重要)


文章目录

  • 【Vue】第十七部分 Vuex、多组件共享数据、四个map方法、namespace、Vuex模块化 (重要)
  • 17. Vuex
    • 17.1 了解Vuex
      • 17.1.1 Vuex是什么?
      • 17.1.2 多组件共享数据---全局事件总线实现
      • 17.1.3 多组件共享数据---Vuex实现
      • 17.1.4 多组件共享状态的问题
    • 17.2 Vuex的工作原理
    • 17.3 Vuex的搭建
      • 17.3.1 准备工作
      • 17.3.2 搭建环境成功示意图
    • 17.4 Vuex案例
    • 17.5 getters 配置项
    • 17.6 四个map方法的使用
      • 17.6.1 mapState方法
      • 17.6.2 mapGetters方法
      • 17.6.3 mapMutations方法
      • 17.6.4 mapActions方法
    • 17.7 多组件共享数据案例
    • 17.8 Vuex模块化和namespace
  • 总结


17. Vuex


17.1 了解Vuex

17.1.1 Vuex是什么?

  1. github 站点
  2. 在线文档
  3. 它是对vue 应用中多个组件的共享状态进行集中式的管理

17.1.2 多组件共享数据—全局事件总线实现


在这里插入图片描述


17.1.3 多组件共享数据—Vuex实现

在这里插入图片描述

17.1.4 多组件共享状态的问题

由上图可以发现,全局事件总线处理多组件共享状态会很麻烦

问题:

  1. 多个视图依赖于同一状态
  2. 来自不同视图的行为需要变更同一状态

所以vuex 就是用来解决上述问题的


17.2 Vuex的工作原理

原理图(下面注释为比喻)
在这里插入图片描述

17.3 Vuex的搭建


17.3.1 准备工作

npm i Vuex@3 案例是使用Vue2所以只能使用Vuex3,到后面使用Vuex3只能使用Vuex4VuexVue都是高一个版本

src/store/index.js

// 导入Vuex
import Vuex from "vuex"
import Vue from "vue"// 使用插件
Vue.use(Vuex)// 准备一个actions对象 --- 响应组件中用户的动作
const actions = {}// 准备一个mutations对象 --- 用来操作数据(state)
const mutations = {}//准备一个state对象 --- 用来保存数据
const state = {}//创建并且暴露 Store 
export default new Vuex.Store({actions,mutations,state
})

main.js

import Vue from "vue"
import store from "./store/index"Vue.config.productionTip = false   //阻止vue在生成时自动产生提示
new Vue({el: '#app',data: {},//配置Storestore,render: h => h(App),beforeCreate(){Vue.prototype.$bus = this  //绑定事件总线}
})

17.3.2 搭建环境成功示意图


在这里插入图片描述

17.4 Vuex案例

案例示图
在这里插入图片描述


main.js

import Vue from "vue"
import App from "./App.vue"
import store from "./store/index"Vue.config.productionTip = false   //阻止vue在生成时自动产生提示\
new Vue({el: '#app',data: {},//配置storestore,render: h => h(App),beforeCreate(){Vue.prototype.$bus = this  //绑定事件总线}
})

src/store/index.js

// 导入Vuex
import Vuex from "vuex"
import Vue from "vue"// 使用插件
Vue.use(Vuex)// 准备一个actions对象 --- 响应组件中用户的动作
const actions = {// plus:function(context,value){}/*第一个参数context:相当于ministore第二个参数value:就是传进来的this.val*/plus(context,value){//console.log(context,value);//console.log("actions");//调用commit去连接mutations //有个小技巧就是写mutation传大写形式,好区分context.commit("PLUS",value)},subtract(context,value){context.commit("SUBTRACT",value)},odd(context,value){if(context.state.sum % 2 != 0)context.commit("PLUS",value)},delay(context,value){setTimeout(()=>{context.commit("PLUS",value)},500)},
}// 准备一个mutations对象 --- 用来操作数据(state)
const mutations = {// plus:function(){}/*第一个参数:代理后的state(是一个对象)第二个参数:就是传进来的this.val*/PLUS(state,value){// console.log(state,value);//console.log("mutations");state.sum += value},SUBTRACT(state,value){state.sum -= value}
}//准备一个state对象 --- 用来保存数据
//有点像data
const state = {sum : 0
}//创建并且暴露 Store 
export default new Vuex.Store({actions,mutations,state
})

count组件

<template><div><h1>当前的值为: {{$store.state.sum}}</h1><select v-model.number="val"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="add"> + </button><button @click="reduce"> - </button><button @click="oddAdd"> 奇数加一 </button><button @click="delayAdd"> 延迟加一 </button></div>
</template><script>
export default {data(){return{val: 1}},methods:{add(){/*调用dispatch,通过dispatch去连接actions*/this.$store.dispatch("plus",this.val)},reduce(){this.$store.dispatch("subtract",this.val)},oddAdd(){this.$store.dispatch("odd",this.val)},delayAdd(){this.$store.dispatch("delay",this.val)},}
}
</script><style>button{margin: 0 8px 0 8px;}
</style>

17.5 getters 配置项

作用:对state中的数据进行加工处理(二次处理数据)

// 准备一个getters配置对象 --- 用于对state中的数据进行加工
// 有点像computed,它也是依靠return进行返回
const getters = {totle(state){return state.sum*10}
}//配置并且暴露
export default new Vuex({...getters
})

17.6 四个map方法的使用

17.6.1 mapState方法


作用:用于帮助我们去映射state中的数据为计算属性

src/store/index.js

...
...
const state = {name:'Tree',gender:'male'age:"18"
}

count组件

当想要调用state中的数据时,需要写一大串的this.$store.state.xxx
例如:自己写的话重复写了很多this.$store.state//computed:{//       name(){//           return this.$store.state.name//      },//       gender(){return this.$store.state.gender//       },//      age(){return this.$store.state.age
//        }
//    }所以这时候就可以使用mapState方法帮我们去映射state中的数据准备工作:需要先导入
import {mapState} from "vuex"
...
<script>export default{// 在computed中使用computed:{//使用ES6扩展运算符将对象拆解成一对对键值(对象写法)// 计算属性名:state中的数据名...mapState({name:"name",gender:"gender",age:"age"}) //(数组写法)需要注意使用数组写法例如:name表示2种意思 计算属性名 和 state中数据的名字要一致...mapState(['name','gender','age'])}}
</script>

要使用数组写法必须满足这样的条件计算属性名state中数据的名字要一致

在这里插入图片描述



17.6.2 mapGetters方法

作用:用于帮助我们去映射getters中的数据为计算属性

准备工作:需要先导入
import {mapGetters} from "vuex"	export default{			   computed: {//借助mapGetters生成计算属性:totoal(对象写法)...mapGetters({totoal:'totoal'}),//借助mapGetters生成计算属性:totoal(数组写法)...mapGetters(['totoal'])}}

17.6.3 mapMutations方法

作用:借助mapMutations帮我们去生成mutations中对应的方法,在该方法中调用commit去联系mutations

import {mapMutations} from "vuex"	
export default{
methods:{//手动写// add(){// /*//     调用dispatch,通过dispatch去连接actions// *///     this.$store.commit("PLUS",this.val)// },// reduce(){//     this.$store.commit("SUBTRACT",this.val)// },/* 借助mapMutations帮我们去生成对应的方法(对象写法)在该方法中调用commit去联系mutations方法名:mutations中的方法名需要注意:如果我们有使用参数要记得传参数,不然mutations并不知道因为我们只写了方法名和actions中的方法名*/...mapMutations({add:'PLUS',reduce:'SUBTRACT'}),// 借助mapMutations帮我们去生成对应的方法(数组写法)// 方法名和actions中的方法名一致//...mapMutations("add","reduce")}
}  



17.6.4 mapActions方法

作用:借助mapMutations帮我们去生成actions中对应的方法,在该方法中调用dispatch去联系actions

import {mapMutations} from "vuex"	
export default{
methods:{//手动写// oddAdd(){//     this.$store.dispatch("odd",this.val)// },// delayAdd(){//     this.$store.dispatch("delay",this.val)// }/* 借助mapActions帮我们去生成对应的方法(对象写法)在该方法中调用dispatch去联系actions方法名:actions中的方法名需要注意:如果我们有使用参数要记得传参数,不然mapActions并不知道因为我们只写了方法名和actions中的方法名*/...mapActions({oddAdd:'odd',delayAdd:'delay'})// 借助mapAction帮我们去生成对应的方法(数组写法)// 方法名和actions中的方法名一致// ...mapActions(['odd','delay'])   }
}  



17.7 多组件共享数据案例

案例示图
在这里插入图片描述

App组件

<template><div><count/><hr><person/></div>
</template><script>
import count from "./components/count.vue"
import person from './components/person.vue'
export default {name:"App",components:{count, person}
}
</script><style>button{margin: 0 6px}
</style>

person组件

<template><div><h1>人员信息</h1><input type="text" placeholder="请输入你想添加的人员信息" v-model="val"@keyup.enter = "addPerson"><ul><li v-for="p in personList" :key="p.id">{{p.name}}</li></ul><h3 style="color:red">count组件计算总和为: {{sum}}</h3></div>
</template><script>
import { mapState } from 'vuex'
import {nanoid} from 'nanoid'
export default {name:"person",data(){return{val:''}},methods:{addPerson(){if(this.val.trim()){const people = {id:nanoid(),name:this.val}this.$store.commit("ADDPERSON",people)this.val = "" }}},computed:{...mapState(['personList',"sum"])}
}
</script><style></style>

count组件

<template><div><h1>统计信息</h1><h2>当前的值为: {{sum}}</h2><select v-model.number="val"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="add(val)"> + </button><button @click="reduce(val)"> - </button><button @click="oddAdd(val)"> 奇数+ </button><button @click="delayAdd(val)"> 延迟+ </button><h3 style="color:red">Person组件总人数为: {{personList.length}}</h3></div>
</template><script>
import { mapActions, mapMutations, mapState } from 'vuex'
export default {name:"count",data(){return{val: 1}},methods:{// 使用mapMutations生成对应的方法...mapMutations({add:"ADD"}),...mapMutations({reduce:"STBTRACT"}),//使用mapActions生成对应的方法...mapActions(["oddAdd","delayAdd"])},computed:{// 使用mapState生成对应的方法...mapState(['sum','personList'])}
}
</script><style ></style>

src/store/index.js

import Vuex from "vuex"
import Vue from "vue"//使用vuex插件
Vue.use(Vuex)// 准备一个actions对象 --- 响应组件中用户的动作
const actions = {oddAdd(ministore,val){if(ministore.state.sum % 2 != 0){ministore.commit("ADD",val)}},delayAdd(ministore,val){setTimeout(()=>{ministore.commit("ADD",val)},500)}
}// 准备一个mutations对象 --- 用来操作数据(state)
const mutations = {ADD(state,val){state.sum += val},STBTRACT(state,val){state.sum -= val},ADDPERSON(state,val){state.personList.push(val)}
}//准备一个state对象 --- 用来保存数据
const state = {sum:0,personList:[{id:"001",name:"张三"}]
}export default new Vuex.Store({actions: actions,mutations: mutations,state: state
})

17.8 Vuex模块化和namespace

对上述的案例进行模块化

作用:便于对代码的更新,有效的进行分类

src/store/index.js

import Vuex from "vuex"
import Vue from "vue"//使用vuex插件
Vue.use(Vuex)//模块化Vuex//求和相关的配置
const countAbout = {//命名空间配置namespaced: true,actions:{oddAdd(ministore,val){if(ministore.state.sum % 2 != 0){ministore.commit("ADD",val)}},delayAdd(ministore,val){setTimeout(()=>{ministore.commit("ADD",val)},500)}},mutations:{ADD(state,val){state.sum += val},STBTRACT(state,val){state.sum -= val}},state:{sum:0},getters:{bigsum(state){return state.sum*10}}
}//人员相关信息的配置
const personAbout = {//命名空间配置namespaced: true,actions:{},mutations:{ADDPERSON(state,val){state.personList.push(val)}},state:{personList:[]},getters:{}
}export default new Vuex.Store({//模块化配置modules:{countAbout,personAbout}
})

person组件

<template><div><h1>人员信息</h1><input type="text" placeholder="请输入你想添加的人员信息" v-model="val"@keyup.enter = "addPerson"><ul><li v-for="p in personList" :key="p.id">{{p.name}}</li></ul><h3 style="color:red">count组件计算总和为: {{sum}}</h3></div>
</template><script>
import { mapState } from 'vuex'
import {nanoid} from 'nanoid'
export default {name:"person",data(){return{val:'',}},methods:{addPerson(){if(this.val.trim()){const people = {id:nanoid(),name:this.val}this.$store.commit("personAbout/ADDPERSON",people)this.val = ""}}},computed:{...mapState('personAbout',['personList']),...mapState('countAbout',['sum'])}
}
</script><style></style>

count组件

<template><div><h1>统计信息</h1><h2>当前的值为: {{sum}}</h2><h2>放大10倍的值: {{bigsum}}</h2><select v-model.number="val"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="add(val)"> + </button><button @click="reduce(val)"> - </button><button @click="oddAdd(val)"> 奇数+ </button><button @click="delayAdd(val)"> 延迟+ </button><h3 style="color:red">Person组件总人数为: {{personList.length}}</h3></div>
</template><script>
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
export default {name:"count",data(){return{val: 1}},methods:{// 使用mapMutations生成对应的方法...mapMutations('countAbout',{add:"ADD"}),...mapMutations('countAbout',{reduce:"STBTRACT"}),//使用mapActions生成对应的方法...mapActions('countAbout',["oddAdd","delayAdd"])},computed:{// 使用mapState生成对应的方法...mapState('countAbout',['sum','personList']),// 使用mapGetters生成对应的方法 ...mapGetters('countAbout',['bigsum']) ,     ...mapState('personAbout',['personList'])       }
}
</script><style ></style>

总结

以上就是今天要讲的内容,本文介绍了Vuex的工作原理、Vuex的搭建、四个map方法的使用、namespace 、Vuex模块化 等等希望对大家有所帮助!!!

这篇关于【Vue】第十七部分 Vuex、多组件共享数据、四个map方法、namespace、Vuex模块化 (重要)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/924393

相关文章

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::