Vue组件间常用的通信方式 您所在的位置:网站首页 vue组件之间的传值有哪几种方式 Vue组件间常用的通信方式

Vue组件间常用的通信方式

2023-11-14 14:46| 来源: 网络整理| 查看: 265

前言

vue组件间的通信是最基础的,也是最重要的知识,在开发中,常用到的组件通信方式有:props与emit、$parent与$children,vuex、以及eventBus,除此之外,还有provide与inject、$attrs与$listeners等。对于向我一样的菜鸟来说,学会用一些常用的通信方式就已经足够了,下面我就来介绍一下这几种vue组件间常用的通信方式。

方法一、props

此方法是父组件A通过props的方式向子组件B传递

接下来我们通过一个例子,说明父组件如何向子组件传递值:在子组件HelloWorld.vue中如何获取父组件App.vue中的数据 msg

//App.vue父组件 import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld } } //HelloWorld子组件 {{ msg }} export default { name: 'HelloWorld', props: { msg: String } }

总结:父组件通过props向下传递数据给子组件。注:组件中的数据共有三种形式:data、props、computed

 

方法二、$emit

此方法是子组件向父组件传值(通过事件形式)

接下来我们通过一个例子,说明子组件如何向父组件传递值。

// HelloWorld子组件 {{title}}//绑定一个点击事件 export default { name: 'HelloWorld', data() { return { title:"Welcome to Your Vue.js App" } }, methods:{ changeTitle() { this.$emit("titleChanged","子向父组件传值");//自定义事件 传递值“子向父组件传值” } } } // App.vue父组件 //与子组件titleChanged自定义事件保持一致 // updateTitle($event)接受传递过来的文字 {{title}} import HelloWorld from "./components/HelloWorld" export default { name: 'App', data(){ return{ title:"传递的是一个值" } }, methods:{ updateTitle(e){ //声明这个函数 this.title = e; } }, components:{ "HelloWorld":HelloWorld, //可简写为一个"HelloWorld" } }

总结:子组件通过events给父组件发送消息,实际上就是子组件把自己的数据发送到父组件。

 

方法三、$parent,$children

通过 $parent,$children 来访问组件实例,进而去获取 或者 改变父子组件的值。 (仅限于父子组件之间,不推荐使用,因为不利于维护,一旦组件层次发生了变化,就需要更改其中的层次关系)

//子组件 {{title}} emit child export default { props: ["title"], methods: { getTitle() { return this.title }, handleClick(){ this.$emit("child","123"); } }, } //父组件 Parent import Child from "./Child"; export default { components: { Child, }, mounted () { // 获取子组件title // console.log(this.$children[0].title); // 修改子组件的title,会有警告 this.$children[0].title = "pass children set value"; console.log(this.$children[0].getTitle()); }, methods: { handleChild(msg) { console.log(msg); } }, }

方法四、$bus总线

这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级。当我们的项目比较大时,可以选择更好的状态管理解决方案vuex。

//A组件 this.$bus.$emit("helloWorld", data); //helloWorld为bus总线名称,data为你要传递过去的数据 //B组件(接收) create() { this.$bus.$on("helloWorld", (res) => { console.log("通过$on接收传过来的数据为:",res) }); } //关闭bus总线 beforeDestroy() { this.$bus.$off("helloWorld"); //注意需要$off来取消监听,否则可能会造成内存泄漏。 },

 

方法五、vuex

集中式存储管理所有组件的状态。 

可以解决 多个视图依赖同一个状态 或者是 来自不同视图的行为需要变更同一个状态 的问题。

State:放状态的地方Mutation:唯一修改状态的地方,不支持异步Action:通过调用Mutation中的方法来达到修改状态的目的,支持异步Getter:可以理解为计算属性Module:模块,每个模块拥有自己的 state、mutation、action、getter

 下面举个例子:

// ./fense/index.vue(A组件) ... this.$store.commit("SET_POLYGONS", val); ... // ./store/modules/fense.js const fense = { state: { polygons: [], //围栏信息 center:{} //展示的中心 }, mutations: { SET_POLYGONS: (state, polygons) => { state.polygons = polygons let polygon = polygons.length > 0 ? polygons[polygons.length - 1] : null; if (!!polygon?.polygonPath) { state.center = polygon.polygonPath[0] } } } } export default fense // ./store/getters.js const getters = { ... polygons:state=>state.fense.polygons, ... } export default getters // ./store/index.js import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' ... import fense from './modules/fense' ... Vue.use(Vuex) const store = new Vuex.Store({ modules: { ... fense, ... }, getters }) export default store // B组件(接收) watch: { "$store.state.fense.center"(value) { this.center.lng = value.lng; this.center.lat = value.lat; this.zoom = 18; }, },

对于小型的项目,通信十分简单,这时使用 Vuex 反而会显得冗余和繁琐,这种情况最好不要使用 Vuex。

方法六、ref

ref 特性可以为子组件赋予一个 ID 引用,通过这个 ID 引用可以直接访问这个子组件的实例。当父组件中需要主动获取子组件中的数据或者方法时,可以使用 $ref 来获取。

Parent import Child from "./Child"; export default { components: { Child, }, mounted () { console.log(this.$refs.compA.getTitle()); this.$refs.input.focus(); }, } {{title}} emit child export default { props: ["title"], methods: { getTitle() { return this.title }, }, }

使用 ref 时,有两点需要注意

$refs 是作为渲染结果被创建的,所以在初始渲染的时候它还不存在,此时无法无法访问。$refs 不是响应式的,只能拿到获取它的那一刻子组件实例的状态,所以要避免在模板和计算属性中使用它。 总结

以上就是我常用的vue组件之间的通信方式,肯定不是所有的,但在工作中会熟练的使用这些方法,也绝对够用了



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有