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 。
新聞熱點
疑難解答
圖片精選