1.通过props方式的传递
2.通过this.$emit()方式传递
在父组件绑定自定义事件,@sendStuent='getStuentName'
注意:组件上绑定原生DOM事件,需要使用native修饰符
3.通过ref方式传递
父组件
<template>
<div id="app">
{{msg}}
<!-- 第一种方式 -->
<School :getSchoolName="getSchoolName"/>
<Student @sendStuent='getStuentName'/>
<my-student ref="student"></my-student>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
import MyStudent from './components/MyStudent.vue'
export default {
name: 'App',
components: {
School,
Student,
MyStudent,
},
data(){
return{
msg:'父组件的数据'
}
},
methods:{
getSchoolName(schoolName){
console.log("App接受的学校名:",schoolName)
},
// ...params用于接收其他参数
getStuentName(studentName,...params){
console.log("App接受的学生名:",studentName,params)
},
getStuentAge(age,...params){
console.log("App接受的学生名:",age,params)
}
},
mounted(){
this.$refs.student.$on('sendStuentAge',this.getStuentAge)
}
}
</script>
子组件(props方式)
<template>
<div class="child">
<p>子组件1</p>
<p>{{name}}</p>
<button @click="sendSchoolName">把子组件的学校名给父组件</button>
</div>
</template>
<script>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'School',
props:['getSchoolName'],
data(){
return{
name:'尚硅谷'
}
},
methods:{
sendSchoolName(){
this.getSchoolName(this.name)
}
}
}
</script>
子组件(this.$emit方式)
<template>
<div class="child">
<p>子组件2</p>
<p>{{name}}</p>
<button @click="sendStudentName">把子组件的学生名给父组件</button>
<button @click="unbind">解绑sendStuent自定义事件</button>
</div>
</template>
<script>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'Student',
data(){
return{
name:'张三'
}
},
methods:{
sendStudentName(){
this.$emit('sendStuent',this.name,11,22,33)
},
// 解绑自定义事件
unbind(){
this.$off('sendStuent') //解绑一个
// this.$off(['sendStuent','demo']) //解绑多个
// this.$off() //所有自定义事件全部解绑
},
death(){
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件完全不奏效
}
}
}
</script>
子组件(ref方式)
<template>
<div class="child">
<p>子组件3</p>
<p>{{age}}</p>
<button @click="sendStudentAge">把子组件的学生年龄给父组件</button>
</div>
</template>
<script>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'Student',
data(){
return{
age:'20'
}
},
methods:{
sendStudentAge(){
this.$emit('sendStuentAge',this.age,11,22,33)
}
}
}
</script>