Vue传递数据 子组件给父组件 自定义组件事件

一、proprs

父组件定义方法->传给子组件(子组件props接收)->子组件通过触发事件给父组件传递的方法赋值->父组件的方法获得值

父组件定义方法

methods: {
    getSchoodata(value){
        this.crossData = value
    }
},

父组件(定义方法)传递给子组件

<SchoolData :getSchoodata='getSchoodata' />

子组件接收

props:['getSchoodata'],

子组件通过事件触发父组件传递的方法,并传值

methods:{
    sendSchoolData(){
        this.getSchoodata(this.name)
    }
}

二、组件自定义事件

1、组件自定义事件绑定

子组件自定义事件->在父组件写绑定事件的方法->在子组件写触发事件(click)->在触发事件中,使用自定义的绑定事件,子组件给父组件传值,父组件接收值

子组件自定义事件

<!-- 自定义事件绑定 -->
<SchoolData @getSchoolData="getSchoolData" />

在父组件写事件的方法

methods:{
    getSchoolData(value){
        // console.log(value)
        this.crossData=value
    }
}

子组件触发实践中,使用自定义组件

methods:{
    // buton点击事件
    sendSchoolData(){
        this.$emit('getSchoolData', this.name)
    }
}

2、组件ref绑定

父组件: 子组件绑定ref->挂载绑定(这里的abc从可以看出tmp)

<StudentData ref="studnetData" />
mounted() {
    this.$refs.studnetData.$on('abc', this.getStudentData)
},

子组件:触发

methods:{
   sendStudentData(){
     this.$emit('abc', this.name)
    // console.log('')
   } 
}

三、解绑

解绑一个

this.$off('abc')

解绑多个

this.$off(['abc', 'a', 'v'])

全部解绑

this.$off()

四、其他

1、组件使用原生的事件处理需要加native

@click.native

2、若只想触发一次

自定义事件.once

ref $on改成$once

 

$on和$once是绑定事件,接收值

$emit触发事件,传值

 

posted @ 2025-01-05 11:33  市丸银  阅读(58)  评论(0)    收藏  举报