Home.vue
<template> <div id="home"> <!--<v-header :_title="title" :homemsg="msg" :homerun="run" :_home="this"></v-header>--> <!--<v-header :_title="title" ></v-header>--> <v-header ref="header"></v-header> 首頁組件 <button @click="getChildData()">獲取子組件的數據和方法</button> </div> </template> <script> /* 父組件給子組件傳值 1、父組件調用子組件的時候,動態綁定屬性 <v-header :_title="title"></v-header> 2、在子組件里面通過props接收父組件傳過來的數據 props:["_title"] props:{"_title" :"String"} 3、直接在子組件里面使用 父組件主動獲取子組件的數據和方法 1、調用子組件的時候定義一個ref <v-header ref="header"></v-header> 2、在父組件里面通過 this.$ref.header.屬性 this.$ref.header.方法 子組件主動獲取父組件的數據和方法 this.$parent.數據 this.$parent.方法 */ import Header from './Header.vue'; export default { name: "Home", data(){ return { // msg:'我是一個Home組件', title:"asddd", msg:'我是home組件' } }, methods:{ run(){ console.log('這是父組件的run方法' ) }, getChildData(){ console.log(this.$refs) console.log(this.$refs.header.msg) this.$refs.header.run() } }, components: { 'v-header' :Header } } </script> <style scoped> </style>
Header.vue
<template> <div> <h2>這是頭部組件</h2> <!--<button @click="homerun('123')">執行父組件的方法</button>--> <!--<button @click="getParent()">獲取父組件的數據和方法</button>--> <button @click="getParentData()">獲取父組件的數據和方法</button> </div> </template> <script> export default { name: "Header", data() { return { msg:'子組件的msg' } }, methods: { run(){ console.log('我是子組件的run方法') }, getParentData(){ /*子組件主動獲取父組件的數據和方法 this.$parent.數據 this.$parent.方法 */ // console.log(this.$parent.msg) this.$parent.run() //調用父組件的run方法 } }, } </script> <style scoped> </style>
運行結果