当前位置:网站首页>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 !
边栏推荐
- How the esp32 deep sleep current is lower than 10uA
- [programming training 2] sorting subsequence + inverted string
- Automated test platform (13): interface automation framework and platform comparison, application scenario analysis and design ideas sharing
- [programming compulsory training 3] find the longest consecutive number string in the string + the number that appears more than half of the times in the array
- C# Newtonsoft.Json中JObject的使用
- Chinese explanation of common rclone subcommands
- [chapter 72 of the flutter problem series] a solution to the problem that pictures taken in the flutter using the camera plug-in are stretched
- go-etcd
- 关于图灵测试和中文屋Chinese room的理解
- Unity2021-Scene视图中物体无法直接选中的解决办法
猜你喜欢

C # read and write customized config file

【编程强训】删除公共字符(哈希映射)+组队竞赛(贪心)

C语言实现【扫雷游戏】完整版(实现源码)

【Tikhonov】基于Tikhonov正则化的图像超分辨率重建

Will Internet talents be scarce in the future? Which technology directions are popular?

ctfshow-web352,353(SSRF)

Félicitations pour l'inscription réussie de wuxinghe

ctfshow-web351(SSRF)

ctfshow-web355,356(SSRF)

如何画产品架构图?
随机推荐
Pourquoi tant de gens sont - ils devenus des gestionnaires de produits? Quelles sont les perspectives de développement des gestionnaires de produits?
Open source! Wenxin large model Ernie tiny lightweight technology, accurate and fast, full effect
【微服务|openfeign】Feign的日志记录
灰度何以跌下神坛?
[recommendation technology] matlab simulation of network information recommendation technology based on collaborative filtering
[classification model] Q-type cluster analysis
Code practice - build your own diffusion models / score based generic models from scratch
继妹变继母,儿子与自己断绝关系,世界首富马斯克,为何这么惨?
Rclone Chinese document: a collection of common commands
C language implementation [Sanzi chess game] (step analysis and implementation source code)
【计网】(一) 集线器、网桥、交换机、路由器等概念
[lingo] find the shortest path problem of undirected graph
Which securities company is better or safer for mobile phone account opening
在长城证券上做基金定投安全吗?
赌上了绩效,赢了公司CTO,我要搭DevOps平台!
JSP - 分页
JAX的深度学习和科学计算
[chapter 72 of the flutter problem series] a solution to the problem that pictures taken in the flutter using the camera plug-in are stretched
C语言实现【扫雷游戏】完整版(实现源码)
ctfshow-web354(SSRF)
