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