Ofbiz模組載入機制即建立獨立模組(脫離熱部署)
阿新 • • 發佈:2022-05-03
-
-
使用場景:A是父元件,B是子元件,B想給A傳資料,那麼就要在A中給B繫結自定義事件(事件的回撥在A中)。
-
繫結自定義事件:
-
第一種方式,在父元件中:
<Demo @atguigu="test"/>
或<Demo v-on:atguigu="test"/>
-
第二種方式,在父元件中:
<Demo ref="demo"/>
-
若想讓自定義事件只能觸發一次,可以使用
once
修飾符,或$once
-
-
觸發自定義事件:
this.$emit('atguigu',資料)
-
解綁自定義事件:
this.$off('atguigu')
-
元件上也可以繫結原生DOM事件,需要使用
native
修飾符。 -
注意:通過
this.$refs.xxx.$on('atguigu',回撥)
繫結自定義事件時,回撥要麼配置在methods中,要麼用箭頭函式
<template> <div class="app"> <h1>{{msg}},學生姓名是:{{studentName}}</h1> <!-- 通過父元件給子元件傳遞函式型別的props實現:子給父傳遞資料 --> <School :getSchoolName="getSchoolName"/> <!-- 通過父元件給子元件繫結一個自定義事件實現:子給父傳遞資料(第一種寫法,使用@或v-on) --> <!-- <Student @atguigu="getStudentName" @demo="m1"/> --> <!-- 通過父元件給子元件繫結一個自定義事件實現:子給父傳遞資料(第二種寫法,使用ref)--> <Student ref="student" @click.native="show"/> </div> </template> <script> import Student from './components/Student' import School from './components/School' export default { name:'App', components:{School,Student}, data() { return { msg:'你好啊!', studentName:'' } }, methods: { getSchoolName(name){ console.log('App收到了學校名:',name) }, getStudentName(name,...params){ console.log('App收到了學生名:',name,params) this.studentName = name }, m1(){ console.log('demo事件被觸發了!') }, show(){ alert(123) } }, mounted() { this.$refs.student.$on('atguigu',this.getStudentName) //繫結自定義事件 // this.$refs.student.$once('atguigu',this.getStudentName) //繫結自定義事件(一次性) }, } </script> <style scoped> .app{ background-color: gray; padding: 5px; } </style>
子元件 : school
<template> <div class="school"> <h2>學校名稱:{{name}}</h2> <h2>學校地址:{{address}}</h2> <button @click="sendSchoolName">把學校名給App</button> </div> </template> <script> export default { name:'School', props:['getSchoolName'], data() { return { name:'尚矽谷', address:'北京', } }, methods: { sendSchoolName(){ this.getSchoolName(this.name) } }, } </script> <style scoped> .school{ background-color: skyblue; padding: 5px; } </style>
子元件 : student
<template> <div class="student"> <h2>學生姓名:{{name}}</h2> <h2>學生性別:{{sex}}</h2> <h2>當前求和為:{{number}}</h2> <button @click="add">點我number++</button> <button @click="sendStudentlName">把學生名給App</button> <button @click="unbind">解綁atguigu事件</button> <button @click="death">銷燬當前Student元件的例項(vc)</button> </div> </template> <script> export default { name:'Student', data() { return { name:'張三', sex:'男', number:0 } }, methods: { add(){ console.log('add回撥被呼叫了') this.number++ }, sendStudentlName(){ //觸發Student元件例項身上的atguigu事件 this.$emit('atguigu',this.name,666,888,900) // this.$emit('demo') // this.$emit('click') }, unbind(){ this.$off('atguigu') //解綁一個自定義事件 // this.$off(['atguigu','demo']) //解綁多個自定義事件 // this.$off() //解綁所有的自定義事件 }, death(){ this.$destroy() //銷燬了當前Student元件的例項,銷燬後所有Student例項的自定義事件全都不奏效。 } }, } </script> <style lang="less" scoped> .student{ background-color: pink; padding: 5px; margin-top: 30px; } </style>