组件通信方式---子传父
组件间通信,子传父相对于父传子来说要稍微麻烦一点,有很多种实现方式。今天来介绍一种最原始的方式。
父组件事先通过props传递给子组件一个函数,子组件利用这个函数给父组件传递数据
父组件
<template>
<div class="school">
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{schoolAddress}}</h2>
<StudentInfo/>
</div>
</template>
<script>
import StudentInfo from './StudentInfo.vue'
export default {
name:'SchoolInfo',
data(){
return {
schoolName:'imufe',
schoolAddress:'内蒙古呼和浩特市'
}
},
components:{
StudentInfo
}
}
</script>
<style>
.school{
background-color: burlywood;
padding: 5px;
margin-top: 5px;
}
</style>
子组件
<template>
<div class="student">
<h3>学生姓名:{{name}}</h3>
<h3>学生年龄:{{age}}</h3>
<h3>学生性别:{{sex}}</h3>
</div>
</template>
<script>
export default {
name:'StudentInfo',
data(){
return {
name:'周佳伟',
age:'22',
sex:'男'
}
}
}
</script>
<style>
.student{
margin: 5px;
background-color: cornflowerblue;
}
</style>
我们在父组件SchoolInfo中准备一个函数,用来接收子组件的数据
methods:{
getStudentName(name,age,sex){
console.log(name);
console.log(age);
console.log(sex);
}
}
之后将这个函数传递给子组件
<StudentInfo :getStudentName='getStudentName'/>
在子组件中接收这个函数
props:['getStudentName'],
我们在子组件一加载完成就使用这个函数,将数据传递给父组件
mounted(){
this.getStudentName(this.name,this.age,this.sex)
}
这样父组件就可以接收到了子组件的数据。