APP收到信息,需要在页面展示
v-on的方式
this.studentName=name
<template>
<div class="app">
<h1>{{msg}},APP收到的学生姓名是:{{studentName}}</h1>
<!-- : 传递的就变成了表达式-->
<!-- Student组件实例对象 绑定了mything事件 mything触发实现的回调函数demo -->
<!-- 通过父组件给子组件绑定自定义事件实现:v-on子给父传递数据 -->
<Student v-on:mything="getStudentName"/>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName"/>
</div>
</template>
<script>
//引入<School/>组件
import Student from './components/Student'
import School from './components/School'
export default {
name: 'App',
data() {
return {
msg:'你好',
studentName:''
}
},
//注册组件
components: {
Student,
School
},
methods: {
getSchoolName(name){
console.log('APP收到了学校名',name)
},
getStudentName(name,...a){
console.log('APP收到了学生名',name,a)
this.studentName=name
},
},
};
</script>
<style>
.app{
background-color: #bfa;
padding: 5px;
}
</style>
ref的方式
<Student ref="student"/>
mounted() {
//收到了组件实例对象 this.$refs.student
this.$refs.student.$on('mything',this.getStudentName)
}
getStudentName(name,...a){
console.log('APP收到了学生名',name,a)
this.studentName=name
},
但是这里有一个注意事项
this.$refs.student.$on('mything',function(...args) {
console.log(this)
})
this是student组件实例,谁触发 this是谁
this是vc了箭头函数没有自己的this ,所以指向了app
this.$refs.student.$on('mything',(...args)=>{
console.log(args)
console.log(this)//vc
this.studentName=args[0]
})
前面都是给组件绑定自定义事件,现在是原生事件
<Student ref="student" @click="show"/>
这种写法变成了自定义事件 需要一个修饰符native
<Student ref="student" @click.native="show"/>