一、場景描述
我們知道綁定自定義事件可以用ref
方式實現(xiàn)。
但是,這個方式,需要注意下,否則,實現(xiàn)不了我們的效果。
需求是這樣的,我們通過ref
綁定的事件,來給App
的data
塊中的變量賦值。
二、綁定自定義事件
基本寫法:
父組件App
中methods
函數(shù):
getStudentName(name,...params){
console.log('App收到了學生名:',name,params)
this.studentName = name
}
給Student
組件綁定自定義事件test
mounted() {
this.$refs.student.$on('test',this.getStudentName) //綁定自定義事件(一次性)
}
此處的this
是誰了?
其實,是Student
組件的vc
實例。Vue
約定,誰觸發(fā)的事件,那么,這個this
就是誰。
但是,此處的this
調用的函數(shù),在App
組件的methods
中,所以,在getStudentName
函數(shù)中的this
,又變成了App
組件的vc
實例。
無效寫法
this.$refs.student.$on('test',function () {
console.log('App收到了學生名:',name,params)
this.studentName = name
})
原因就是,此時function
里面的this
是Student
的vc
實例,無法獲取到studentName
變量,所以,賦值失敗。
改進寫法:文章來源:http://www.zghlxwxcb.cn/news/detail-806446.html
//這種寫法,可以給studentName變量賦值。
this.$refs.student.$on('test',(name,...params) => {
console.log('App收到了學生名:',name,params)
this.studentName = name
})
換成箭頭函數(shù),就可以實現(xiàn)基本寫法的效果。為什么了?
因為,箭頭函數(shù)沒有自己的this
,于是,Vue
需要向外部尋找,這是,找到的this
就是App
組件的vc
實例。
從而實現(xiàn)對studentName
變量的賦值。文章來源地址http://www.zghlxwxcb.cn/news/detail-806446.html
到了這里,關于Vue2:用ref方式綁定自定義事件的注意事項的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!