<template> <div class="app"> <h1>{{msg}}</h1> <!-- props 子给父传递事件 --> <School :getSchoolName="getSchoolName"/> <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 (第一种写法,使用@过v-on)--> <!-- <Student v-on:aiguigu="demo"/> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 (第二种写法,使用ref) --> <Student ref="student" /> </div> </template>
<script> import Student from './components/Student.vue' import School from './components/School.vue' export default{ name:'App', components:{ School,Student }, data(){ return{ msg:'你好啊!' } }, methods: { getSchoolName(name){ console.log('收到学校名',name) }, demo(name){ console.log('demo被调用了!',name) } }, mounted(){ //比较灵活 setTimeout(()=>{ this.$refs.student.$on('atguigu',this.demo) },3000) } } </script>
<style> .app{ background-color: gray; } </style> <template> <div class="school"> <h2 >学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="sendSchoolName">把学校名给APP</button> </div> </template>
<script> export default{ name:'School', data() { return { name:'尚硅谷', address:'北京' } }, props:['getSchoolName'], methods: { sendSchoolName(){ this.getSchoolName(this.name) } }, } </script>
<style> .school{ background-color: aqua; } </style> <template> <div class="student"> <h2 >学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <button @click="sendStudentName">点我把学生名给APP</button> <button @click="unbind">解绑事件</button> </div> </template>
<script>
export default{ name:'Student', data() { return { name:'张三', sex:'男' } }, methods: { sendStudentName(){ //触发Student组件实例身上的aiguigu事件 this.$emit('atguigu',this.name) }, unbind(){ this.$off('atguigu') //解绑单个事件 //this.$off(['atguigu',...])解绑多个 } }, } </script>
<style> .student{ background-color: pink; } </style>
标签:School,vue,name,08,绑定,Student,atguigu,methods From: https://www.cnblogs.com/hbro/p/18041225