iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 8
0
Modern Web

技術在走,Vue.js 要有系列 第 8

|D8| 從原始碼看 Vue 元件化 (1) - 概念介紹


圖片來源:Vue.js

元件化就是把頁面拆成一個ㄧ個元件( component ),然後像積木ㄧ樣把頁面組合起來,例如可能有導航列、側邊欄、table 等 component。

  • component 只要維護自己依賴的 css、js 等資源就好

  • component 是可重複用的 Vue 實例,從創建到銷毀會經過一系列的 lifecycle hooks

  • component 有自己的 data、computed、watch、methods 等

  • component 需註冊(全域註冊或本地註冊)才能使用,需指定名稱

  • 每次使用 component 都會創建該元件的新實例,例如點擊按鈕元件時,每個按鈕是獨立計算 count

    Vue.component('button-counter', {
      data: function () {
        return {
          count: 0
        }
      },
      template: '<button v-on:click="count++">點擊次數:{{ count }} 次</button>'
    })
    
    <div id="components-demo">
      <button-counter></button-counter>
      <button-counter></button-counter>
      <button-counter></button-counter>
    </div>
    

以 Vue-cli3 初始化的進入點來說,前幾篇提到 Vue 實例是通過 render 方法渲染成真正的 DOM,但此處丟入 createElement 方法的參數是一個 component,不是一個原生 html tag。下一篇從 createComponent 來看 Vue 是如何運作 component 的createComponent

// min.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  
  // h 是 createElement 方法
  render: h => h(App)
}).$mount("#app");

上一篇
|D7| 從原始碼看 Vue 渲染機制 (5) - $mount
下一篇
|D9| 從原始碼看 Vue 元件化 (2) - createComponent
系列文
技術在走,Vue.js 要有30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言