Vue 中的父子通信和事件触发
一、组件
子组件
<template>
<div style="border:1px solid black;width:400px; height: 130px;">
<h3>我是子组件</h3>
<button>子组件将值传递给父组件</button>
<div>子组件接收父组件的值:</div>
</div>
</template>
复制代码
父组件
<template>
<div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
<h3>我是父组件</h3>
<div>子组件向父组件传递的值:</div>
<Child></Child>
</div>
</template>
<script>
import Child from './Child';
export default {
components: {
Child
}
}
</script>
复制代码
效果展示: 通过这张图可以看出父子组件的结构,下面我们来实习父子组件通信。
二、父子组件通信
父组件给子组件通信
实现思路:子组件通过 props
来接受父组件传过来的值。
-
在父组件中,定义一个data变量,在子组件标签中动态绑定这个值。
// Father.vue <template> <div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;"> <h3>我是父组件</h3> <div>子组件向父组件传递的值:{{ChildMsg}}</div> <Child :FatherMsg="data"></Child> </div> </template> <script> import Child from './Child'; export default { data() { return { data: 'I am your father', } }, components: { Child } } </script> 复制代码
-
接着在子组件里通过
props
来接收,这样子组件就接收到了父组件传递过来的值了。// Child.vue <template> <div style="border:1px solid black;width:400px; height: 130px;"> <h3>我是子组件</h3> <button>子组件将值传递给父组件</button> <div>父组件向子组件传递的值:{{FatherMsg}}</div> </div> </template> <script> export default { data() { return { data: 'I am your children', } }, props: ['FatherMsg'] } </script> 复制代码
可以看到,我们父组件向子组件通信已经实现了,接下来就是子组件向父组件通信了,这个就要使用到 this.$emit
方法了。
子组件向父组件通信
实现思路:通过在子组件中使用 this.$emit
来触发自定义事件并传值,然后在父组件中监听该事件即可。
-
在子组件中给 button 按钮添加 click 事件,来通过
this.$emit
自定义事件,并传入一个参数:<template> <div style="border:1px solid black;width:400px; height: 130px;"> <h3>我是子组件</h3> <button @click="send">子组件将值传递给父组件</button> <div>父组件向子组件传递的值:{{FatherMsg}}</div> </div> </template> <script> export default { data() { return { data: 'I am your children', } }, props: ['FatherMsg'], methods: { send() { this.$emit('ListenChild', this.data); } } } </script> 复制代码
-
在父组件中的子组件标签里,先在
data
里定义一个变量接收这个值,然后监听在子组件中自定义的事件,并接受这个参数赋值给定义的变量:<template> <div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;"> <h3>我是父组件</h3> <div>子组件向父组件传递的值:{{ChildMsg}}</div> <Child :FatherMsg="data" @ListenChild="ListenChild"></Child> </div> </template> <script> import Child from './Child'; export default { data() { return { data: 'I am your father', ChildMsg: '', } }, components: { Child }, methods: { ListenChild(data) { console.log("子组件传递过来的值:" , data); this.ChildMsg = data; } } } </script> 复制代码
点击子组件中的“子组件将值传递给父组件”,就可看到如下效果:
三、父子组件事件触发
父组件调用子组件中的事件方法
-
通过
ref
直接调用子组件的方法:// Child.vue <template> <div style="border: 1px solid black; width: 150px; margin: 10px auto"> 我是子组件 <div style="color: red"> {{ msg }} </div> </div> </template> <script> export default { data() { return { msg: '', } }, methods: { childFun() { console.log('我是子组件的方法 childFun'); this.msg = '我的方法被调用了' }, }, }; </script> 复制代码
在子组件标签上添加
ref
属性,然后在方法中通过this.$refs
找到绑定ref
的属性调用该子组件内的方法即可。// Father.vue <template> <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto"> 我是父组件 <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child" /> </div> </template> <script> import Child from './Child'; export default { components: { Child }, methods: { handleClick() { this.$refs.child.childFun(); }, }, } </script> 复制代码
-
通过组件的
$emit
、$on
方法:// Child.vue <template> <div style="border: 1px solid black; width: 150px; margin: 10px auto"> 我是子组件 <div style="color: red"> {{ msg }} </div> </div> </template> <script> export default { data() { return { msg: '', } }, mounted() { this.$on('childFun', function() { console.log('我是子组件方法'); this.msg = '我的方法被调用了' }); } }; </script> 复制代码
在子组件中使用
$on
绑定一个方法,然后在父组件中通过$emit
找到绑定$on
上面的事件名即可,但是也需要ref
的配合。// Father.vue <template> <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto"> 我是父组件 <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child" /> </div> </template> <script> import Child from './Child'; export default { components: { Child }, methods: { handleClick() { //子组件$on中的名字 this.$refs.child.$emit("childFun") }, }, } </script> 复制代码
两种实现方式效果一致。
调用方法前: 调用方法后:
子组件调用父组件中的事件方法
-
直接在子组件中通过
this.$parent
来调用父组件的方法// Father.vue <template> <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" > 我是父组件 <Child></Child> <div style="color: red"> {{ msg }} </div> </div> </template> <script> import Child from './Child'; export default { data() { return { msg: '' } }, components: { Child }, methods: { fatherMethod() { console.log('我的父组件中的方法'); this.msg = '我的方法被子组件调用了'; } } }; </script> 复制代码
// Child.vue <template> <div style="border: 1px solid black; width: 150px; margin: 10px auto"> 我是子组件 <button @click="childMethod">点击调用父组件方法</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } }; </script> 复制代码
-
在子组件里用
$emit
向父组件触发一个事件,父组件监听这个事件(推荐使用)// Father.vue <template> <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" > 我是父组件 <Child @fatherMethod="fatherMethod"></Child> <div style="color: red"> {{ msg }} </div> </div> </template> <script> import Child from './Child'; export default { data() { return { msg: '' } }, components: { Child }, methods: { fatherMethod() { console.log('我的父组件中的方法'); this.msg = '我的方法被子组件调用了'; } } }; </script> 复制代码
子组件可以使用
$emit
触发父组件的自定义事件。// Child.vue <template> <div style="border: 1px solid black; width: 150px; margin: 10px auto"> 我是子组件 <button @click="childMethod">点击调用父组件方法</button> </div> </template> <script> export default { methods: { childMethod() { // fatherMethod父组件方法 this.$emit('fatherMethod'); } } }; </script> 复制代码
-
父组件把方法传入子组件中,在子组件里直接调用这个方法:
// Father.vue <template> <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" > 我是父组件 <Child :fatherMethod="fatherMethod"></Child> <div style="color: red"> {{ msg }} </div> </div> </template> <script> import Child from './Child'; export default { data() { return { msg: '' } }, components: { Child }, methods: { fatherMethod() { console.log('我的父组件中的方法'); this.msg = '我的方法被子组件调用了'; } } }; </script> 复制代码
父组件可以将事件绑定到子组件标签上,子组件使用
props
接收父组件的事件。// Child.vue <template> <div style="border: 1px solid black; width: 150px; margin: 10px auto"> 我是子组件 <button @click="childMethod">点击调用父组件方法</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); } } } }; </script> 复制代码
以上三种实现方式效果一致。
调用方法前: 调用方法后:
四、总结
至此,Vue 父子组件之间大部分的操作都涉及到了,我们在程序的开发过程中对于该部分内容可以游刃有余了。
推荐阅读
-
在Vue3和Vue Router中,如何实现在切换到同一页面后自动刷新并触发特定操作的技巧
-
异步编程RxJava-介绍-前言 前段时间写了一篇对协程的一些理解,里面提到了不管是协程还是callback,本质上其实提供的是一种异步无阻塞的编程模式;并且介绍了java中对异步无阻赛这种编程模式的支持,主要提到了Future和CompletableFuture;之后有同学在下面留言提到了RxJava,刚好最近在看微服务设计这本书,里面提到了响应式扩展(Reactive extensions,Rx),而RxJava是Rx在JVM上的实现,所有打算对RxJava进一步了解。 RxJava简介 RxJava的官网地址:https://github.com/ReactiveX/RxJava, 其中对RxJava进行了一句话描述:RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM. 大意就是:一个在Java VM上使用可观测的序列来组成异步的、基于事件的程序的库。 更详细的说明在Netflix技术博客的一篇文章中描述了RxJava的主要特点: 1.易于并发从而更好的利用服务器的能力。 2.易于有条件的异步执行。 3.一种更好的方式来避免回调地狱。 4.一种响应式方法。 与CompletableFuture对比 之前提到CompletableFuture真正的实现了异步的编程模式,一个比较常见的使用场景: CompletableFuture<Integer> future = CompletableFuture.supplyAsync(耗时函数); Future<Integer> f = future.whenComplete((v, e) -> { System.out.println(v); System.out.println(e); }); System.out.println("other..."); 下面用一个简单的例子来看一下RxJava是如何实现异步的编程模式: Observable<Long> observable = Observable.just(1, 2) .subscribeOn(Schedulers.io).map(new Func1<Integer, Long> { @Override public Long call(Integer t) { try { Thread.sleep(1000); //耗时的操作 } catch (InterruptedException e) { e.printStackTrace; } return (long) (t * 2); } }); observable.subscribe(new Subscriber<Long> { @Override public void onCompleted { System.out.println("onCompleted"); } @Override public void onError(Throwable e) { System.out.println("error" + e); } @Override public void onNext(Long result) { System.out.println("result = " + result); } }); System.out.println("other..."); Func1中以异步的方式执行了一个耗时的操作,Subscriber(观察者)被订阅到Observable(被观察者)中,当耗时操作执行完会回调Subscriber中的onNext方法。 其中的异步方式是在subscribeOn(Schedulers.io)中指定的,Schedulers.io可以理解为每次执行耗时操作都启动一个新的线程。 结构上其实和CompletableFuture很像,都是异步的执行一个耗时的操作,然后在有结果的时候主动告诉我结果。那我们还需要RxJava干嘛,不知道你有没有注意,上面的例子中其实提供2条数据流[1,2],并且处理完任何一个都会主动告诉我,当然这只是它其中的一项功能,RxJava还有很多好用的功能,在下面的内容会进行介绍。 异步观察者模式 上面这段代码有没有发现特别像设计模式中的:观察者模式;首先提供一个被观察者Observable,然后把观察者Subscriber添加到了被观察者列表中; RxJava中一共提供了四种角色:Observable、Observer、Subscriber、Subjects Observables和Subjects是两个被观察者,Observers和Subscribers是观察者; 当然我们也可以查看一下源码,看一下jdk中的Observer和RxJava的Observer jdk中的Observer: public interface Observer { void update(Observable o, Object arg); } RxJava的Observer: public interface Observer<T> { void onCompleted; void onError(Throwable e); void onNext(T t); } 同时可以发现Subscriber是implements Observer的: public abstract class Subscriber<T> implements Observer<T>, Subscription 可以发现RxJava中在Observer中引入了2个新的方法:onCompleted和onError onCompleted:即通知观察者Observable没有更多的数据,事件队列完结 onError:在事件处理过程中出异常时,onError会被触发,同时队列自动终止,不允许再有事件发出。 正是因为RxJava提供了同步和异步两种方式进行事件的处理,个人觉得异步的方式更能体现RxJava的价值,所以这里给他命名为异步观察者模式。 好了,下面正式介绍RxJava的那些灵活的操作符,这里仅仅是简单的介绍和简单的实例,具体用在什么场景下,会在以后的文章中介绍 Maven引入
-
在 Vue 中使用 Slot 插槽是组件中的实用必备知识,它还能实现父组件和子组件之间的通信。
-
Vue中Slot槽的使用,让我们一起来学习!父组件和子组件之间也可以通信
-
Vue 中的父子通信和事件触发
-
Vue 的父子组件通信和事件触发(最完整的实用总结)
-
vue 中 $emit 和 $on 父子组件和同级组件之间的通信
-
Vue]Vue 中的父子组件通信以及使用 sync 同步父子组件数据
-
vue3]07 - vue 组件之间的通信 - 父子组件之间的相互传输 - 事件总线 - Vue 的组件嵌套
-
vue 中事件直通和不允许直通示例的详细解释