国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue組件實例間的直接訪問實現代碼

2024-05-06 15:12:37
字體:
來源:轉載
供稿:網友

前面的話

  有時候需要父組件訪問子組件,子組件訪問父組件,或者是子組件訪問根組件。 在組件實例中,Vue提供了相應的屬性,包括$parent、$children、$refs和$root,這些屬性都掛載在組件的this上。本文將詳細介紹Vue組件實例間的直接訪問

$parent 

  $parent表示父組件的實例,該屬性只讀

  下面是一個簡易實例

<div id="example"> <parent-component></parent-component></div><template id="parent-component"> <div class="parent"> <h3>我是父組件</h3> <input v-model="parentMsg"> <p>{{parentMsg}}</p> <child-component></child-component>  </div></template><template id="child-component"> <div class="child"> <h3>我是子組件</h3> <p>{{msg}}</p> <button v-on:click="showData">顯示父組件數據</button>  </div></template>
<script>// 注冊Vue.component('parent-component', { template: '#parent-component', data(){ return{  parentMsg:'我是父組件的數據' } }, components:{ 'child-component':{  template:'#child-component',  data(){  return{   msg:''  }  },  methods:{  showData(){   this.msg = this.$parent.parentMsg;  }  } } }})// 創建根實例new Vue({ el: '#example'})</script>

$root 

  $root表示當前組件樹的根 Vue 實例。如果當前實例沒有父實例,此實例將會是其自己。該屬性只讀

<div id="example"> <h3>我是根組件</h3> <input v-model="rootMsg"> <p>{{rootMsg}}</p>  <parent-component></parent-component></div><template id="parent-component"> <div class="parent"> <h3>我是父組件</h3> <input v-model="parentMsg"> <p>{{parentMsg}}</p> <child-component></child-component>  </div></template><template id="child-component"> <div class="child"> <h3>我是子組件</h3> <p>  <button v-on:click="showRootData">顯示根組件數據</button><span>{{rootMsg}}</span> </p>   <p>  <button v-on:click="showParentData">顯示父組件數據</button><span>{{parentMsg}}</span> </p> </div></template>
<script>// 注冊Vue.component('parent-component', { template: '#parent-component', data(){ return{  parentMsg:'我是父組件的數據' } }, components:{ 'child-component':{  template:'#child-component',  data(){  return{   parentMsg:'',   rootMsg:''  }  },  methods:{  showParentData(){   this.parentMsg = this.$parent.parentMsg;  },  showRootData(){   this.rootMsg = this.$root.rootMsg;  },    } } }})// 創建根實例new Vue({ el: '#example', data:{ rootMsg:'我是根組件數據' }})</script>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 镇宁| 天津市| 革吉县| 兴国县| 类乌齐县| 天水市| 通渭县| 正阳县| 新竹县| 招远市| 龙南县| 安新县| 普洱| 舒城县| 昭苏县| 扶沟县| 高淳县| 尚义县| 边坝县| 上虞市| 上林县| 乌苏市| 涞水县| 裕民县| 体育| 白水县| 农安县| 县级市| 额敏县| 叶城县| 巴塘县| 台江县| 佛冈县| 嵊州市| 青海省| 七台河市| 平度市| 应城市| 崇阳县| 汕尾市| 内黄县|