一、場景描述
我們在頁面開發(fā)中,難免要使用事件。
在之前的學習中,我們學過@click、@keyup、@change
等事件,這些是Vue
自帶的事件。
它一般是用在原生的HTML元素上的。在組件上使用需要加native
修飾
比如:
h1綁定一個click事件:
<h1 @click="test">你好</h1>
input綁定一個keyup事件:
<input type="text" @keyup.enter="add"/>
在組件上綁定一個Vue原生事件:
<School @change.native="delete"/>
這一篇說的自定義事件,可以綁定到我們自己的Vue
組件上。
實現(xiàn)子組件給父組件傳遞數(shù)據(jù)的功能。
比如:
<School :getSchoolName="getSchoolName"/>
二、綁定自定義事件
方式1
使用@或v-on
方式綁定自定義事件
App
父組件中:
模板代碼:
<Student @test="getStudentName"/>
methods
函數(shù):
getStudentName(name,...params){
console.log('App收到了學生名:',name,params)
}
Student
子組件中:
模板代碼:
<button @click="sendStudentlName">把學生名給App</button>
methods
函數(shù):
sendStudentlName(){
//觸發(fā)Student組件實例身上的test事件
this.$emit('test',this.name,666,888,900)
}
方式2
使用ref
方式綁定自定義事件App
父組件中:
模板代碼:
<Student ref="student"/>
mounted
屬性:
mounted() {
//設(shè)置三秒后再綁定事件
// setTimeout(() => {
// this.$refs.student.$on('test',this.getStudentName) //綁定自定義事件 第一個參數(shù)是事件名稱,第二個參數(shù)是函數(shù)名稱
// },3000);
// this.$refs.student.$on('test',this.getStudentName) //綁定自定義事件 第一個參數(shù)是事件名稱,第二個參數(shù)是函數(shù)名稱
this.$refs.student.$once('test',this.getStudentName) //綁定自定義事件(一次性)
}
Student
子組件中:
和方式1
相同文章來源:http://www.zghlxwxcb.cn/news/detail-803757.html
三、總結(jié)
原則:給那個組件的vc
實例綁定事件,就由那個組件的vc
實例來觸發(fā)事件
相對來講,第二種方法更靈活,第一種方法更簡便,各有優(yōu)勢,視具體情況選擇使用。文章來源地址http://www.zghlxwxcb.cn/news/detail-803757.html
到了這里,關(guān)于Vue2:給組件綁定自定義事件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!