DIV CSS 佈局教程網

Vue.js 組件與組件通信完整指南
編輯:關於JavaScript     

組件的基本概念

組件是 Vue.js 中可重複使用的介面單元。它能封裝模板、資料與行為,讓複雜頁面可以拆成多個可維護的小單元。

註冊組件

可以透過 Vue.component 全域註冊,也可以在父組件的 components 選項中局部註冊。

Vue.component('my-component', {
  template: '<div>這是一個組件</div>'
});
const Child = Vue.extend({
  template: '<div>子組件</div>'
});

const Parent = Vue.extend({
  components: {
    'my-component': Child
  }
});

使用 props 傳遞資料

組件作用域預設是獨立的,父組件若要把資料傳給子組件,應透過 props。

Vue.component('child', {
  props: ['msg'],
  template: '<span>{{ msg }}</span>'
});
<child msg="hello"></child>

若要傳遞動態表達式,可使用 v-bind:

<child :msg="parentMessage"></child>

父子組件通信

子組件可以透過事件通知父組件。做法是子組件觸發自訂事件,父組件使用 v-on 監聽。

<child v-on:child-msg="handleMessage"></child>
Vue.component('child', {
  template: '<button v-on:click="notify">送出訊息</button>',
  methods: {
    notify: function () {
      this.$emit('child-msg', '來自子組件的訊息');
    }
  }
});

使用 slot 分發內容

Slot 允許父組件把內容插入子組件模板中。

<my-component>
  <p>這段內容會被插入子組件</p>
</my-component>

子組件模板:

template: '<div><slot></slot></div>'

動態組件

使用 <component :is="..."> 可以在多個組件之間切換。

<component :is="currentView"></component>

若希望切換後保留狀態,可加上 keep-alive:

<component :is="currentView" keep-alive></component>

異步組件

大型應用可以把組件延後載入。Vue.js 允許把組件定義為工廠函數。

Vue.component('async-example', function (resolve) {
  setTimeout(function () {
    resolve({
      template: '<div>異步組件</div>'
    });
  }, 1000);
});

遞歸組件

組件可以在自己的模板中引用自己,但需要 name 與終止條件。

const StackOverflow = Vue.extend({
  name: 'stack-overflow',
  template: '<div><stack-overflow v-if="condition"></stack-overflow></div>'
});

片斷實例

如果模板有多個根節點、只有文字,或根節點帶有流程控制指令,可能形成片斷實例。實務上建議讓組件模板保持單一根節點,以確保屬性、事件與過渡能正確作用。

總結

Vue.js 組件的強大之處在於:props 負責輸入資料、事件負責對外通知、slot 負責內容組合。掌握這三者,就能建立清楚且可重用的元件架構。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved