vue組件父子間通信詳解(三)
本文實例為大家分享了vue組件父子間通信的具體代碼,供大家參考,具體內(nèi)容如下
三、組件間通信($parent $refs)
父組件要想獲取子組件的數(shù)據(jù):
①在調(diào)用子組件的時候,指定ref屬性
<child-component ref="mySon"></child-component>
②根據(jù)指定的引用的名字 找到子組件的實例對象
this.$refs.mySon
子組件要想獲取父組件的數(shù)據(jù):
①直接讀取
this.$parent
通過this.$refs拿到子組件的數(shù)據(jù)
代碼:
<!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拿到指定的所引用的對應(yīng)的組件的實例對象 getSonName:function(){ this.mySonName = this.$refs.mySon.name; } }, template:` <div> <h1>這是父組件</h1> <button @click = "getSonName">獲取子組件數(shù)據(jù)</button> <span>{{mySonName}}</span> <hr> <xiaohua ref="mySon"></xiaohua> </div> ` }) // 創(chuàng)建子組件 Vue.component("xiaohua",{ data:function(){ return{ name:"小花" } }, template:` <h1>這是子組件</h1> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
子組件通過$parent獲取父組件的數(shù)據(jù)
<!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> //創(chuàng)建子組件 Vue.component("dahua",{ data:function(){ return{ myName:"大花" } }, template:` <div> <h1>這是父組件</h1> <hr> <xiaohua></xiaohua> </div> ` }) //創(chuàng)建子組件 Vue.component("xiaohua",{ data:function(){ return{ msg:"" } }, template:` <div> <h1>這是子組件</h1> <p>{{msg}}</p> </div> `, created:function(){ //在子組件創(chuàng)建完成時獲取父組件的數(shù)據(jù) //保存在msg中在p標(biāo)簽中顯示 this.msg = this.$parent.myName; } }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
VUEJS 2.0 子組件訪問/調(diào)用父組件的實例
下面小編就為大家分享一篇VUEJS 2.0 子組件訪問/調(diào)用父組件的實例。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02vue主動刷新頁面及列表數(shù)據(jù)刪除后的刷新實例
今天小編就為大家分享一篇vue主動刷新頁面及列表數(shù)據(jù)刪除后的刷新實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09如何用vue3+Element?plus實現(xiàn)一個完整登錄功能
要實現(xiàn)用戶的登錄功能,可以使用Vue3和Element?Plus,下面這篇文章主要給大家介紹了關(guān)于如何基于Vue3和Element?Plus組件庫實現(xiàn)一個完整的登錄功能,文中提供了詳細(xì)的代碼示例,需要的朋友可以參考下2023-10-10使用vite創(chuàng)建vue3項目的詳細(xì)圖文教程
創(chuàng)建Vue3項目有兩種常見的方式,一種是想vue2版本一樣使用腳手架工具創(chuàng)建,創(chuàng)建vue3項目的腳手架必須是4版本以上的,另一種方法就是使用vite創(chuàng)建,這篇文章主要給大家介紹了關(guān)于如何使用vite創(chuàng)建vue3項目的相關(guān)資料,需要的朋友可以參考下2022-11-11iview tabs 頂部導(dǎo)航欄和模塊切換欄的示例代碼
這篇文章主要介紹了iview tabs 頂部導(dǎo)航欄和模塊切換欄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03