<template> <!-- 全部的內容要被根節點包含起來 --> <div id="home"> <v-header ref="header"></v-header> <hr> 首頁組件 <button @click="getChildData()">獲取子組件的數據和方法</button> </div> </template> <script> /* 父組件給子組件傳值 1.父組件調用子組件的時候 綁定動態屬性 <v-header :title="title"></v-header> 二、在子組件裏面經過 props接收父組件傳過來的數據 props:['title'] props:{ 'title':String } 3.直接在子組件裏面使用 父組件主動獲取子組件的數據和方法: 1.調用子組件的時候定義一個ref <v-header ref="header"></v-header> 2.在父組件裏面經過 this.$refs.header.屬性 this.$refs.header.方法 子組件主動獲取父組件的數據和方法: this.$parent.數據 this.$parent.方法 */ import Header from './Header.vue'; export default{ data(){ return { msg:'我是一個home組件', title:'首頁111' } }, components:{ 'v-header':Header }, methods:{ run(){ alert('我是Home組件的run方法'); }, getChildData(){ //父組件主動獲取子組件的數據和方法: // alert(this.$refs.header.msg); this.$refs.header.run(); } } } </script> <style lang="scss" scoped> /*css 局部做用域 scoped*/ h2{ color:red } </style>
<template> <div> <h2>我是頭部組件</h2> <button @click="getParentData()">獲取子組件的數據和方法</button> </div> </template> <script> export default{ data(){ return{ msg:'子組件的msg' } }, methods:{ run(){ alert('我是子組件的run方法') }, getParentData(){ /* 子組件主動獲取父組件的數據和方法: this.$parent.數據 this.$parent.方法 */ // alert(this.$parent.msg); //this.$parent.run(); } } } </script>