Vue 子组件向父组件传递数据的三种方式

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

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

methods: {
     getSchoolName(name) {

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

    }

}

子组件:
<button @click="sendSchoolName">把学校名给App</button>
 props: ['getSchoolName'],
methods: {

      sendSchoolName() {

        this.getSchoolName(this.name)

      }

}

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

父组件:

 <StudentCm name="张三" :age="18" v-on:wxj="getStudentName"></StudentCm>
methods: {
    getStudentName() {

        console.log('demo被调用了')

     }
}

子组件:
<button @click="sendStudentName">把学生名给App</button>
methods: {
    sendStudentName() {

        // 触发Student组件实例身上的wxj事件

        this.$emit('wxj')

    }

}

3.通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref)
   说明:这种方式虽然麻烦,但是更灵活,可以使用setTimeout控制响应时间。

父组件:
<StudentCm name="李四" ref="student"></StudentCm>
 mounted(){

      setTimeout(() =>{

        // 函数体

        this.$refs.student.$on('wxj', this.getStudentName)

      }, 3000)

},
methods: {
    getStudentName(name) {

        console.log('App收到了学生名:', name)

     }

}

子组件:
<button @click="sendStudentName">把学生名给App</button>
methods: {

sendStudentName() {

        // 触发Student组件实例身上的wxj事件

        this.$emit('wxj')

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容