Header.vue
1 <template> 2 3 4 <div> 5 6 <h2>我是头部组件</h2> 7 8 9 <button @click="getParentData()">获取子组件的数据和方法</button> 10 11 12 </div> 13 </template> 14 15 16 17 18 <script> 19 20 export default{ 21 22 23 data(){ 24 25 return{ 26 msg:'子组件的msg' 27 } 28 }, 29 methods:{ 30 31 run(){ 32 33 alert('我是子组件的run方法') 34 }, 35 getParentData(){ 36 37 38 /* 39 子组件主动获取父组件的数据和方法: 40 41 42 this.$parent.数据 43 44 this.$parent.方法 45 46 47 */ 48 // alert(this.$parent.msg); 49 50 //this.$parent.run(); 51 } 52 } 53 54 } 55 56 </script>
Home.vue
1 <template> 2 <!-- 所有的内容要被根节点包含起来 --> 3 <div id="home"> 4 5 <v-header ref="header"></v-header> 6 7 <hr> 8 首页组件 9 10 <button @click="getChildData()">获取子组件的数据和方法</button> 11 12 </div> 13 14 </template> 15 16 17 <script> 18 19 20 /* 21 父组件给子组件传值 22 23 1.父组件调用子组件的时候 绑定动态属性 24 <v-header :title="title"></v-header> 25 26 2、在子组件里面通过 props接收父组件传过来的数据 27 props:['title'] 28 29 30 31 props:{ 32 33 'title':String 34 } 35 36 3.直接在子组件里面使用 37 38 39 40 父组件主动获取子组件的数据和方法: 41 42 1.调用子组件的时候定义一个ref 43 44 <v-header ref="header"></v-header> 45 46 2.在父组件里面通过 47 48 this.$refs.header.属性 49 50 this.$refs.header.方法 51 52 53 54 55 56 子组件主动获取父组件的数据和方法: 57 58 59 this.$parent.数据 60 61 this.$parent.方法 62 63 64 65 */ 66 67 import Header from './Header.vue'; 68 69 export default{ 70 data(){ 71 return { 72 msg:'我是一个home组件', 73 title:'首页111' 74 } 75 }, 76 components:{ 77 78 'v-header':Header 79 }, 80 methods:{ 81 82 run(){ 83 84 alert('我是Home组件的run方法'); 85 }, 86 getChildData(){ 87 88 //父组件主动获取子组件的数据和方法: 89 // alert(this.$refs.header.msg); 90 91 this.$refs.header.run(); 92 } 93 } 94 95 96 } 97 98 </script> 99 100 <style lang="scss" scoped> 101 102 /*css 局部作用域 scoped*/ 103 104 h2{ 105 106 color:red 107 } 108 109 110 </style>