vue組件父子間通信02
阿新 • • 發佈:2017-11-02
doctype class vue.js vuejs logs ets 獲取 gets ack
三、組件間通信($parent $refs)
父組件要想獲取子組件的數據:
①在調用子組件的時候,指定ref屬性
<child-component ref="mySon"></child-component>
②根據指定的引用的名字 找到子組件的實例對象
this.$refs.mySon
子組件要想獲取父組件的數據:
①直接讀取
this.$parent
:::通過this.$refs拿到子組件的數據
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>組件間通信-01</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <dahua></dahua> </div> <script> //vue提供的ref Vue.component("dahua",{ data:function(){ return{ mySonName:"" } }, methods:{ //通過$refs拿到指定的所引用的對應的組件的實例對象 getSonName:function(){ this.mySonName = this.$refs.mySon.name; } }, template:`<div> <h1>這是父組件</h1> <button @click = "getSonName">獲取子組件數據</button> <span>{{mySonName}}</span> <hr> <xiaohua ref="mySon"></xiaohua> </div> ` }) // 創建子組件 Vue.component("xiaohua",{ data:function(){ return{ name:"小花" } }, template:` <h1>這是子組件</h1> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
子組件通過$parent獲取父組件的數據
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>組件間通信-02</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <dahua></dahua> </div> <script> //創建子組件 Vue.component("dahua",{ data:function(){ return{ myName:"大花" } }, template:` <div> <h1>這是父組件</h1> <hr> <xiaohua></xiaohua> </div> ` }) //創建子組件 Vue.component("xiaohua",{ data:function(){ return{ msg:"" } }, template:` <div> <h1>這是子組件</h1> <p>{{msg}}</p> </div> `, created:function(){ //在子組件創建完成時獲取父組件的數據 //保存在msg中在p標簽中顯示 this.msg = this.$parent.myName; } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
vue組件父子間通信02