vue組件父子間通訊詳解(三),vue父子
本文執行個體為大家分享了vue組件父子間通訊的具體代碼,供大家參考,具體內容如下
三、組件間通訊($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>
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。