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

首頁 > 語言 > JavaScript > 正文

詳解vue2.0組件通信各種情況總結與實例分析

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

Props在vue組件中各種角色總結

在Vue中組件是實現模塊化開發的主要內容,而組件的通信更是vue數據驅動的靈魂,現就四種主要情況總結如下:

使用props傳遞數據---組件內部

//html<div id="app1">  <i>注意命名規定:僅在html內使用my-message</i>  <child my-message="組件內部數據傳遞"></child></div>//js<script>  Vue.component('child', {    props: ['myMessage'],    template: '<mark>{{ myMessage }}<mark/>'  });  new Vue({    el: '#app1'  })</script>

動態props通信---組件與根節點(父子之間)

<div id="app2">  <input v-model="parentMsg">  <br>  <child :parent-msg="parentMsg"></child></div><script>  Vue.component('child', {    props: ['parentMsg'],    template: '<mark>{{ parentMsg }}<mark/>'  });  new Vue({    el: '#app2',    data: {      parentMsg: 'msg from parent!'    }  })</script>

對比分析:

例子1:

<comp some-prop="1"></comp>//組件內部數據傳遞,對應字面量語法:傳遞了一個字符串"1" 

例子2:

<comp v-bind:some-prop="1"></comp>//組件與根節點數據傳遞,對應動態語法:傳遞實際的數字:js表達式 

單向數據流動特點:父組件屬性變化時將傳導給子組件,反之不可

兩種改變prop情況

注意在 JavaScript 中對象和數組是引用類型,指向同一個內存空間,如果 prop 是一個對象或數組,在子組件內部改變它會影響父組件的狀態。

//定義一個局部data屬性,并將 prop 的初始值作為局部數據的初始值props: ['initialCounter'],    data: function () {    return { counter: this.initialCounter }    }//定義一個局部computed屬性,此屬性從 prop 的值計算得出 props: ['size'],    computed: {    normalizedSize: function () {    return this.size.trim().toLowerCase()    }    }

子組件索引

盡管有 props 和 events ,但是有時仍然需要在 JavaScript 中直接訪問子組件。為此可以使用 ref 為子組件指定一個索引 ID

<div id="parent"><!-- vm.$refs.p will be the DOM node --><b ref="p">hello</b><!-- vm.$refs.child will be the child comp instance --><user-profile v-for='i in 3' ref="profile"></user-profile></div><script>var userPf=Vue.component('user-profile',{  template:'<div>hello $refs</div>'});var parent = new Vue({ el: '#parent' });// 訪問子組件var child = parent.$refs.profile;console.log(child[0]);console.log(parent.$refs.p);</script>

$refs 只在組件渲染完成后才填充,并且它是非響應式的。它僅僅作為一個直接訪問子組件的應急方案——應當避免在模版或計算屬性中使用 $refs 。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 梅河口市| 伊宁县| 嫩江县| 通许县| 大冶市| 临猗县| 海口市| 清苑县| 江城| 儋州市| 仲巴县| 岱山县| 萍乡市| 阜宁县| 南木林县| 甘德县| 泾川县| 新蔡县| 集贤县| 开远市| 南京市| 扶绥县| 和硕县| 福清市| 修文县| 府谷县| 香河县| 包头市| 阿拉善右旗| 孝昌县| 武陟县| 绥宁县| 容城县| 新化县| 上栗县| 宜阳县| 南通市| 响水县| 南通市| 海原县| 曲靖市|