Vue组件中子给父传递数据的三种方法

116 阅读2分钟

在写TodoList案例的过程中遇到了需要子给父传递数据的问题。之前只是使用props完成了数据传递,接下来介绍一下Vue组件中子给父传递数据的三种方法。

通过父组件给子组件传递函数类型的props实现:子给父传递数据

比如:App.vue是School.vue的父组件。为了实现点击按钮提示名称,利用这种方法,我们需要给School标签绑定一个函数,在App.vue的methods中定义该方法,而在School标签中写的名称相当于传递中介,在School.vue中需要在props中声明拿到了这个方法。
<School :getSchoolName="getSchoolName"/>
getSchoolName(name){
    console.log('App收到了学校名:',name)
}

以下写在School.vue中

<button @click="sendSchoolName">把学校名给App</button>
sendSchoolName(){
    this.getSchoolName(this.name)
}

通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on)

使用v-on或@给子组件绑定一个自定义事件,同样的在父组件中也要在method中添加方法,与上一种方法的区别就是在子组件使用时不需要另外声明接收了,可以直接调用,不过形式上还是有差别,详见代码。
<Student @getName="getStudentName"/>//此处的getName为自定义事件名称
getStudentName(name,...params){
    console.log('App收到了学生名:',name,params)//params是拿多个参数(数组形式)
}

以下写在Student.vue中

<button @click="sendStudentlName">把学生名给App</button>
sendStudentlName(){
    //触发Student组件实例身上的atguigu事件
    this.$emit('getName',this.name,666,888,900)
}

通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref)

与上一种方法大同小异,只是使用了ref,并且利用mounted来绑定自定义事件。
<Student ref="student"/>//在App.vue中使用this.$refs.student可以拿到Student组件的实例对象
mounted() {
    this.$refs.student.$on('getName',this.getStudentName) //绑定自定义事件
    // this.$refs.student.$once('getName',this.getStudentName) //绑定自定义事件(一次性)
}

在Student.vue中的配置与上一种一样。这种方法的好处就是灵活性很强,比如可以设置定时器,使得经过一段时间才绑定事件。