第一种:父组件给子组件传递函数类型的props实现
父组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <template> <div id="root"> <School :add = "add" /> <Student /> </div> </template> import School from "./components/School.vue"; import Student from './components/Student.vue' export default { name: "App", data() { return { }; }, components:{ School, Student }, methods:{ add(x){ console.log(x) } } };
|
子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <div id="root"> <button @click="add(msg)">点击传递</button> </div> </template> export default { name: "App", props:['add'], data() { return { msg:'123' }; }, components:{ }, methods:{
} };
|
父组件向子组件传递一个函数,然后子组件通过props接收函数,然后调用向父组件传值
第二种:通过父组件给子组件自定义事件,子组件$emit发射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <template> <div id="root"> <School @add = "add" /> <Student /> </div> </template> import School from "./components/School.vue"; import Student from './components/Student.vue' export default { name: "App", data() { return { }; }, components:{ School, Student }, methods:{ add(x){ console.log(x) } } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div id="root"> <button @click="dianji">点击传递</button> </div> </template> export default { name: "App", data() { return { msg:'123' }; }, components:{ }, methods:{ dianji(){ this.$emit('add',this.msg) } } };
|
第三种:给子组件绑定ref属性,父组件在mounted用$on给子组件绑定事件,子组件$emit发射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <div id="root"> <School ref = "school" /> <Student /> </div> </template> import School from "./components/School.vue"; import Student from './components/Student.vue'; export default { name: "App", data() { return { }; }, components:{ School, Student }, methods:{ add(x){ console.log(x) } }, mounted() { this.$refs.school.$on('add',this.add) } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <template> <div id="root"> <button @click="dianji">点击传递</button> </div> </template> export default { name: "App", data() { return { msg:'123' }; }, components:{
}, methods:{ dianji(){ this.$emit('add',this.msg) } } };
|
自定义事件解绑
直接点击组件响应
直接点击组件需要使用@click.native修饰符
如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !