前言
組件是 vue.js 最強大的功能之一,而組件實例的作用域是相互獨立的,這就意味著不同組件之間的數據無法相互引用。如何傳遞數據也成了組件的重要知識點之一。
組件
組件與組件之間,還存在著不同的關系。父子關系與兄弟關系(不是父子的都暫稱為兄弟吧)。
父子組件
父子關系即是組件 A 在它的模板中使用了組件 B,那么組件 A 就是父組件,組件 B 就是子組件。
// 注冊一個子組件Vue.component('child', { data: function(){ text: '我是father的子組件!' } template: '<span>{{ text }}</span>'})// 注冊一個父組件Vue.component('father', { template: '<div><child></child></div>' // 在模板中使用了child組件})直接使用 father 組件的時候:
<div id="app"> <father></father></div>
頁面中就會渲染出 :我是father的子組件!
father 組件在模板中使用了 child 組件,所以它就是父組件,child 組件被使用,所以 child 組件就是子組件。
兄弟組件
兩個組件互不引用,則為兄弟組件。
Vue.component('brother1', { template: '<div>我是大哥</div>'})Vue.component('brother2', { template: '<div>我是小弟</div>'})使用組件的時候:
<div id="app"> <brother1></brother1> <brother2></brother2></div>
頁面中就會渲染出 :
我是大哥
我是小弟
Prop
子組件想要使用父組件的數據,我們需要通過子組件的 props 選項來獲得父組件傳過來的數據。以下我使用在 .vue 文件中的格式來寫例子。
如何傳遞數據
在父組件 father.vue 中引用子組件 child.vue,把 name 的值傳給 child 組件。
<template> <div class="app"> // message 定義在子組件的 props 中 <child :message="name"></child> </div></template><script> import child from './child.vue'; export default { components: { child }, data() { return { name: 'linxin' } } }</script>在子組件 child.vue 中的 props 選項中聲明它期待獲得的數據
<template> <span>Hello {{message}}</span></template><script> export default { // 在 props 中聲明獲取父組件的數據通過 message 傳過來 props: ['message'] }</script>那么頁面中就會渲染出:Hello linxin
單向數據流
當父組件的 name 發生改變,子組件也會自動地更新視圖。但是在子組件中,我們不要去修改 prop。如果你必須要修改到這些數據,你可以使用以下方法:
新聞熱點
疑難解答
圖片精選