当前位置:网站首页>Custom events of components ②
Custom events of components ②
2022-07-01 07:19:00 【18 hate programming】
List of articles
The unbundling of events
First of all, it is not necessary to declare the unbinding of the event , But he must have recommended . This is the same as turning off the timer , As long as we open it, we should choose a suitable time to close it , But you don't , Just waiting for the user to close the web page , It's OK, too .
We unbind the event on the basis of the previous article .
The syntax used for unbinding :$off( Event name )
Be careful : Where is the bound , Where to unbind
The code implementation is as follows :
<template>
<div class="demo">
<h2 class="stu" > Student name :{
{name}}</h2>
<h2 > Student age :{
{age}}</h2>
<button @click="studentNameGetter(name)"> Click to give the student name to the parent component App</button>
<button @click="unbind"> Click unbind event </button>
</div>
</template>
<script> export default {
name:'MyStudent', data(){
return {
name:' Zhang San ', age:18 } }, methods:{
studentNameGetter(name){
// Trigger Student Component instance stuName event this.$emit('stuName',name) }, unbind(){
this.$off('stuName') } } } </script>
But the above method can only unbind one custom event , If we have multiple custom events that need to be unbound , Pass in an array in the above method :
$off([' event 1',‘ event 2’,......])
Tips:
$off()
If nothing , All custom events on this component instance will be unbound
Point review :
In the process of destruction vm Yes $destroy() after , Will turn off all listeners , Child components , And event listeners . At this time, the original DOM Events can use , Because what he removed was the event listener for custom events .
Two points of attention
$on() In the method this Direction problem of
App Components
<template>
<div>
<h2 ref="title" > Welcome to {
{n}}</h2>
<hr>
<SchoolName :getSchoolName="getSchoolName"></SchoolName>
<StudentName ref="Student"></StudentName>
<!-- <StudentName v-on:stuName="getStudentName"></StudentName>-->
<!-- <StudentName @stuName ="getStudentName"></StudentName>-->
</div>
</template>
<script> import SchoolName from "@/components/School"; import StudentName from "@/components/Student"; export default {
components:{
SchoolName, StudentName }, data(){
return {
n:'CSDN' } }, methods:{
getSchoolName(name){
console.log('App The component has received the name of the school :',name) }, getStudentName(name){
console.log('App The component has received the student's name :',name) } }, mounted() {
this.$refs.Student.$on('stuName',this.getStudentName) } } </script>
stay $on() Since the second parameter in the method we passed in is a function , Then can we directly define the function in on In the method , Not in methods As defined in ?
App Components :
<script> import SchoolName from "@/components/School"; import StudentName from "@/components/Student"; export default {
components:{
SchoolName, StudentName }, data(){
return {
n:'CSDN' } }, methods:{
getSchoolName(name){
console.log('App The component has received the name of the school :',name) }, // getStudentName(name){
// console.log('App The component has received the student's name :',name) // } }, mounted() {
this.$refs.Student.$on('stuName',function (name) {
console.log(this) console.log('App The component has received the student's name :',name) }) } } </script>


We found that this The direction of is not App
Be careful : Who triggered this event , here $on() In the method this Point to who
The impact of this situation is if we want to mount the data passed from the child component to the current parent component , You will find that you cannot mount , Because at this time this The point of is no longer the parent component
So how can we solve this problem ? The two methods :
- Like before , Write the callback method in methods in
- take $on() The callback method passed in the method is written as an arrow function . Because the arrow function doesn't have its own this, So I looked out , and mounted() Function this Has been maintained as the current component , That is to say App, So it's feasible .
The code is as follows :
<script> import SchoolName from "@/components/School"; import StudentName from "@/components/Student"; export default {
components:{
SchoolName, StudentName }, data(){
return {
n:'CSDN' } }, methods:{
getSchoolName(name){
console.log('App The component has received the name of the school :',name) }, // getStudentName(name){
// console.log('App The component has received the student's name :',name) // } }, mounted() {
this.$refs.Student.$on('stuName',(name) => {
console.log(this) console.log('App The component has received the student's name :',name) }) } } </script>
At this time this Namely App Component :
Binding misunderstanding
We are binding some native to the component DOM At the time of the event , You will find that it cannot be triggered , This is because Vue All events bound to components will be treated as custom events .

So how can we solve this problem ? Use .native Event modifier :
So this event can be regarded as the original DOM Events to resolve .
His bottom layer is a click The incident was handed over to Student The outermost element of the component .
Student Components :
That's the big one div.
This also confirms a fact from the side : Component's template There can only be one root element !
If there are more than one , Your click Who should the event be given ?( Of course, this is just one of the confirmation directions )
Custom event summary of component
Custom events for components
A way of communicating between components , Apply to : Child components ===> Parent component
Use scenarios :A It's the parent component ,B It's a subcomponent ,B Want to give A The data transfer , Then it's in A Middle feeding B Binding custom events ( The callback of the event is in A in ).
Binding custom events :
The first way , In parent component :
<Demo @eventName="test"/>or<Demo v-on:eventName="test"/>The second way , In parent component :
<Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('eventName',this.test) }If you want a custom event to be triggered only once , have access to
onceModifier , or$onceMethod .
Trigger custom event :
this.$emit('eventName', data )Unbind custom events
this.$off('eventName')Components can also be bound to native DOM event , Need to use
nativeModifier .Be careful : adopt
this.$refs.xxx.$on('eventName', Callback )When Binding custom events , Callbacks are either configured in methods Or use the arrow function , otherwise this There will be problems !
边栏推荐
- Apple账号密码自动填充
- [lingo] find the minimum connection diagram of seven cities to minimize the price of natural gas pipelines
- Illusory and simple screen raindrop post-processing effect
- Redisson utilise la solution complète - redisson Documents officiels + commentaires (Partie 1)
- Which securities company is better or safer for mobile phone account opening
- Paging in servlets and JSPS
- 女生适合学产品经理吗?有什么优势?
- 运维管理系统,人性化操作体验
- 电脑有网络,但所有浏览器网页都打不开,是怎么回事?
- Open source! Wenxin large model Ernie tiny lightweight technology, accurate and fast, full effect
猜你喜欢
![[lingo] find the minimum connection diagram of seven cities to minimize the price of natural gas pipelines](/img/34/d2efae5b283cdc130d55f52cdff76d.png)
[lingo] find the minimum connection diagram of seven cities to minimize the price of natural gas pipelines

【目标检测】目标检测界的扛把子YOLOv5(原理详解+修炼指南)

【电气介数】电气介数及考虑HVDC和FACTS元件的电气介数计算
![[Shenzhen IO] precise Food Scale (some understanding of assembly language)](/img/8c/1e64401e812538d8606df557054355.png)
[Shenzhen IO] precise Food Scale (some understanding of assembly language)

赌上了绩效,赢了公司CTO,我要搭DevOps平台!

JSP - paging
![[programming training 2] sorting subsequence + inverted string](/img/96/87750c5d3954ef6c39cce073e8b9ae.png)
[programming training 2] sorting subsequence + inverted string

为什么这么多人转行产品经理?产品经理发展前景如何?
![[programming training] delete public characters (hash mapping) + team competition (greedy)](/img/cd/63eb9da1e8956df0763797f079b67f.png)
[programming training] delete public characters (hash mapping) + team competition (greedy)

LeetCode+ 71 - 75
随机推荐
华泰证券开户是安全可靠的么?怎么开华泰证券账户
C# 读写自定义的Config文件
Is it safe to do fund fixed investment on Great Wall Securities?
【电气介数】电气介数及考虑HVDC和FACTS元件的电气介数计算
Is it safe and reliable for Huatai Securities to open an account? How to open Huatai Securities Account
MySQL and redis consistency solution
1286_FreeRTOS的任务优先级设置实现分析
Jax's deep learning and scientific computing
发现了一个 MySQL 的巨坑:update 更新别再用影响行数做判断了!!!
比赛即实战!中国软件杯发布全新产业创新赛项,校企可联合参赛
Do securities account opening affect the security of account opening
Paging in servlets and JSPS
[programming training 2] sorting subsequence + inverted string
Rclone configuring Minio and basic operations
weback5基础配置详解
【Tikhonov】基于Tikhonov正则化的图像超分辨率重建
开源了!文心大模型ERNIE-Tiny轻量化技术,又准又快,效果全开
[lingo] solve quadratic programming
【目标检测】目标检测界的扛把子YOLOv5(原理详解+修炼指南)
redisson使用全解——redisson官方文档+注释(上篇)
