Vue子传父的三种方法
区别在代码中已标出
1.props方式
父组件内容
<template> <div class="app"> <h1>{{msg}}</h1>
<!-- : 可替换为 v-bind: --> <CustomSchool :childEvent="getSchoolName"/>
</div> </template> <script> // 引入子组件 import CustomSchool from '@/components/3Custom/CustomSchool.vue' export default { components: { CustomSchool}, data() { return { msg: '你好啊!' } }, methods:{ getSchoolName(data){ this.msg = data } } } </script>
子组件内容
<template> <div class="school"> <div> 学校名称:{{name}}</div> <div> 学校地址:{{address}} </div> <button @click="sendSchoolName">把学校名发送给父组件</button> </div> </template> <script> export default { props:['childEvent'],
data() { return { name: 'rxy', address: '北京' } }, methods:{ sendSchoolName(){ this.childEvent(this.name)
}
}
}
</script>
2.this.$emit方式(绑定自定义事件)
父组件内容
<template> <div class="app"> <h1>{{msg}} </h1>
<!-- @ 可替换为 v-on: -->
<CustomSchool @childEvent="getSchoolName"/> </div> </template> <script> import CustomSchool from '@/components/3Custom/CustomSchool.vue' export default { components: { CustomSchool}, data() { return { msg: '你好啊' } }, methods:{ getSchoolName(data){ this.msg = data } } } </script>
子组件内容
<template> <div class="school"> <div> 学校名称:{{name}}</div> <div> 学校地址:{{address}} </div> <button @click="sendSchoolName">把学校名发送给App</button>
<button @click="unbind">解绑自定义事件</button>
</div> </template> <script> export default { data() { return { name: 'rxy', address: '北京' } }, methods:{ sendSchoolName(){ this.$emit('childEvent',this.name) },
unbind() {
// this.$off('childEvent') //适用于解绑单个事件
// this.$off(['childEvent', 'demo']) //解绑多个自定义事件
this.$off() //解绑所有自定义事件
},
}
}
</script>
3.使用eventBus(更灵活) 例:可用定时器
父组件内容,通过ref方式获取
<template> <div class="app"> <h1> {{msg}} </h1> <CustomSchool ref="school" /> </div> </template> <script> import CustomSchool from '@/components/3Custom/CustomSchool.vue' export default { components: { CustomSchool}, data() { return { msg: '你好啊' } }, mounted() { setTimeout(() => { this.$refs.school.$on('schoolEvent', e => { this.msg = e }) }, 3000)
// this.$refs.student.$on('studentEvent',this.getSchoolName) //两种方式都可以
}, methods: {
getSchoolName(data) {
this.msg = data
},
}
}
</script>
子组件内容
<template> <div class="school"> <div> 学校名称:{{name}}</div> <div> 学校地址:{{address}} </div> <button @click="sendSchoolName">把学校名发送给App</button> </div> </template> <script> export default { data() { return { name: 'rxy', address: '北京' } }, methods: { sendSchoolName() { this.$emit('schoolEvent',this.name) } } } </script>