props子给父传值 子组件的自定义事件

props子给父传值

 <School :getSchoolName="getSchoolName"/>                //父组件

methods: {

  getSchoolName(name){

 console.log('App收到了学校名',name);

  }},

子组件

export default {

props:['getSchoolName'],

data(){

    return {name:'尚硅谷',address:'北京'}},

methods: {

    sendSchoolName(){

       this.getSchoolName(this.name) }},}

子组件的自定义事件

适用于    子组件 ===> 父组件

绑定一个自定义事件实现: 子给父传递数据   第一种方法   使用@ 或v-on

 <Student v-on:atguigu="getStudentName"/>

<Student @atguigu.once="getStudentName"/>         //只触发一次

methods: {

  getStudentName(name, ...params ){        //...params把所有传递过来的参数放到params里面

    console.log('demo被调用了',name); }},

子组件

methods: {

    sendStudentName(){

      this.$emit('atguigu',this.name)},},     //触发Student组件实例身上的 atguigu

绑定一个自定义事件实现: 子给父传递数据   第二种方法 使用ref

父组件

<Student ref="student"/>

mounted() {

  this.$refs.student.$on('atguigu',this.getStudentName)       //可以加定时器

 this.$refs.student.$once('atguigu',this.getStudentName)     //只触发一次

},

子组件

methods: {

    sendStudentName(){

      this.$emit('atguigu',this.name)},},   //触发Student组件实例身上的 atguigu


解绑自定义事件

<button @click="unbind">解绑atguigu事件</button>

unbind(){

  this.$off('atguigu')    //解绑一个自定义事件

   this.$off(['atguigu','demo']) //解绑多个自定义事件

this.$off()  //解绑所有自定义事件

    }

若想让自定义事件只触发一次可以使用 once修饰符 或$once方法

触发自定义事件  this.$emit('auguigu',数据)

组件上也可以绑定原生DOM事件,需要使用native修饰符

 <Student ref="student" @click.native="show"/>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容