vue組件父子間通訊詳解(三),vue父子

來源:互聯網
上載者:User

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>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.