课程参考尚硅谷Vue全家桶
components:
Student.vue
<template>
<!-- 组件的结构 -->
<div class="student">
<h2>学生姓名:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给App</button>
</div>
</template>
<script>
//组件交互相关的代码(数据、方法等)
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'Student',
props:['getStudentName'],
data(){
return {
studentName:'张三',
age:18
}
},
methods:{
sendStudentName(){
//触发Student组件实例身上的atguigu事件
this.$emit('getStudentName',this.studentName)
}
}
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
School.vue
<template>
<!-- 组件的结构 -->
<div class="school">
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="sendSchoolName">把学校名给App</button>
</div>
</template>
<script>
//组件交互相关的代码(数据、方法等)
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'School',
data(){
return {
schoolName:'xxx大学',
address:'北京',
}
},
props:['getSchoolName'],
methods:{
sendSchoolName(){
this.getSchoolName(this.schoolName)
}
}
}
</script>
<style scoped>
.school{
background-color: skyblue;
padding: 5px;
}
</style>
App.vue
<template>
<div class="app">
<h1>{{msg}}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName" />
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据(第一种写法,使用@ 或 v-on) -->
<!-- <Student @getStudentName = "getStudentName"/> -->
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据(第二种写法,使用ref) -->
<Student ref="student"/>
</div>
</template>
<script>
import School from '../src/components/School.vue'
import Student from './components/Student.vue';
export default {
name:'App',
data() {
return {
msg:'你好啊'
};
},
components: { School, Student },
methods:{
getSchoolName(name){
console.log('App收到了学校名:',name);
},
getStudentName(stuName){
console.log('App收到了学生名:',stuName);
}
},
mounted() {
this.$refs.student.$on('getStudentName',this.getStudentName)
},
}
</script>
<style scoped>
.app{
background-color: #ddd;
padding: 5px;
}
</style>
组件的自定义事件
-
一种组件间通信的方式,适用于:子组件 ===> 父组件
-
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
-
绑定自定义事件:
-
第一种方式,在父组件中:
<Demo @getStudentName="test"/>
或<Demo v-on:getStudentName="test"/>
-
第二种方式,在父组件中:
<Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('getStudentName',this.test) }
-
若想让自定义事件只能触发一次,可以使用
once
修饰符,或$once
方法。
-
-
触发自定义事件:
this.$emit('getStudentName',数据)
-
解绑自定义事件
this.$off('getStudentName')
-
组件上也可以绑定原生DOM事件,需要使用
native
修饰符。 -
注意:通过
this.$refs.xxx.$on('getStudentName',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!