app組件的代碼
<template> <div class="d1"> <!-- 兩種子給父傳值的方法 -->
<!-- 第一種是父給子先傳遞函數 子組件要用props接收數據,然后調用函數,給父組件返回值--> <MyStudent :getStudentName="getStudentName"></MyStudent>
<!-- 第二種是父親給子定義自定義函數,子組件只需要用this.$emit('aiguigu',返回值) 觸發函數就可以了,這時父親就可以收到返回值 --> <MySchool v-on:aiguigu="getSchoolName"></MySchool> </div> </template> <script> import MyStudent from './components/MyStudent.vue' import MySchool from './components/MySchool.vue' export default { name:'App', components:{ MyStudent, MySchool }, data() { return { } }, methods: { getStudentName(name){ console.log('我收到了來自學生的名字',name) }, getSchoolName(name){ console.log('我收到了來自學校的名字',name); } }, } </script>
MyStudent的代碼
<template> <div id='student'> <h2>我的名字是:{{name}}</h2> <h2>我的年齡是:{{age}}</h2> <button @click="sentStudentName">點我給app發送名字</button> </div> </template> <script> export default { name:'MyStudent', data() { return { name:'王哥', age:'23' } }, //接受app傳過來的函數 props:['getStudentName'],//記得加分號 methods: { //把學生姓名傳回去 sentStudentName(){ this.getStudentName(this.name) } }, } </script>
MySchool的代碼
<template> <div id="school"> <h2>學校名字是{{name}}</h2> <h2>學校地址是{{address}}</h2> <button @click="sentSchoolName">點我調用app的demo函數</button> </div> </template> <script> export default { name:'MySchool', data() { return { name:'廣州****大學', address:'廣州' } }, methods: { sentSchoolName(){ this.$emit('aiguigu',this.name) } }, } </script>