创建一个子组件,并在父组件中使用
1.student子组件
<template>
<div class="hello">
<h1>学生信息</h1>
<h2>姓名:{{ name }}</h2>
<h2>性别:{{ sex }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>成绩:{{ gread }}</h2>
<button @click="sendParent">点击给父组件传递姓名</button>
</div>
</template>
<script>
//创建student子组件
export default {
name: 'HelloWorld',
//引用父组件中定义的
props:['sendChildDate'],
data(){
return{
name:'张三',
sex:'男',
age:18,
gread:100
}
},
methods:{
sendParent(){
this.sendChildDate(this.name)
}
}
}
</script>
<style scoped>
.hello{
background: red;
margin-left: 20px;
margin-top: 10px;
width: 260px;
}
</style>
2.APP父组件
在父组件中:定义一个接受子组件的函数(命名方式=》:子组件发送数据时调用的方法名=‘父组件接收数据时调用的方法名’)
<template>
<div id="app">
<h1>父组件</h1>
<HelloWorld :sendChildDate="getChildDate"/>
<h1 >子组件传递过来的数据是:{{ childrenValu }}</h1>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
props:{},
components: {
HelloWorld
},
data(){
return{
childrenValu:''
}
},
methods:{
getChildDate(name){
this.childrenValu=name
console.log(this.childrenValu);
}
}
}
</script>
<style>
#app{
background-color: bisque;
width: 600px;
}
</style>
实现效果:点击按钮,可以将子组件的name数据传递到父组件中