Vue.js 中的 new Vue() 與 Vue.createApp():從 Vue 2 到 Vue 3 的演進

更新日期: 2024 年 11 月 16 日

Vue.js 作為一個流行的前端框架,從 Vue 2 到 Vue 3 發生了許多架構上的變化。

其中一個重要改進是應用實例的創建方式,從 Vue 2 的 new Vue() 到 Vue 3 的 Vue.createApp(),這不僅體現了設計理念的進化,也解決了在開發過程中遇到的一些實際問題。


Vue 2:new Vue()

在 Vue 2 中,我們使用 new Vue() 來創建 Vue 實例。

範例

const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue 2!'
  }
});

意涵

  1. 創建實例new Vue() 創建了一個 Vue 應用實例。
  2. 綁定元素el: '#app' 將 Vue 應用掛載到 HTML 中的 ID 為 app 的元素上。
  3. 管理數據data 定義了應用的狀態,在此例中是 message

Vue 3:createApp()

在 Vue 3 中,我們使用 createApp() 方法來創建 Vue 應用。

範例(使用解構賦值)

import { createApp } from 'vue';

const app = createApp({
  data() {
    return {
      message: 'Hello Vue 3!'
    };
  }
});

app.mount('#app');

範例(不使用解構賦值)

import Vue from 'vue'; // 假設不使用解構賦值

const app = Vue.createApp({
  data() {
    return {
      message: 'Hello Vue 3!'
    };
  }
});

app.mount('#app');

意涵

  1. 創建應用Vue.createApp() 返回一個應用實例。
  2. 掛載元素:使用 .mount('#app') 將應用綁定到 HTML 中的 ID 為 app 的元素上。
  3. 管理數據data 定義應用的狀態,類似 Vue 2。

Vue 2 與 Vue 3 的主要差異

Vue 2 和 Vue 3 在應用實例的管理和全域 API 的設計上有明顯的不同。

用生活化的比喻來說:

  • Vue 2 的 new Vue():像是一間大房子裡的房間,所有房間共享一個公共空間(全域配置)。

    如果在這個空間裡改變了一個設定,所有房間都會受到影響。

    比如,所有房間只能掛一個統一的窗簾。
  • Vue 3 的 createApp():像是一棟大樓裡的多間套房,每間套房都有自己的私人空間(應用實例),互不干擾。

    如果你改變了某一間套房的窗簾顏色,其他套房的窗簾不會受到影響。

應用實例的獨立性

Vue 2 的限制

在 Vue 2 中,所有的 Vue 實例共享相同的全域配置,這意味著它們在某些情況下可能互相影響,無法真正獨立運行。

const app1 = new Vue({
  el: '#app1',
  data: { message: 'App 1' }
});

const app2 = new Vue({
  el: '#app2',
  data: { message: 'App 2' }
});

即使這樣創建了兩個應用,它們仍然會共享一些全域設定,比如自定義指令。

Vue 3 的改進

在 Vue 3 中,每個由 createApp() 創建的應用實例是完全獨立的,可以在同一頁面中運行多個應用而不互相影響。

const app1 = Vue.createApp({
  data() {
    return { message: 'App 1' };
  }
}).mount('#app1');

const app2 = Vue.createApp({
  data() {
    return { message: 'App 2' };
  }
}).mount('#app2');

每個應用實例有自己的配置,完全獨立,彼此不干涉。


全域 API 的變化

Vue 2 的全域 API

在 Vue 2 中,全域 API(如 Vue.componentVue.directive)是基於 Vue 的全域命名空間定義的,這意味著它們會影響所有 Vue 實例。

例如:

Vue.component('global-component', {
  template: '<p>This is a global component</p>'
});

這會讓所有 Vue 實例都可以使用該全域元件。

Vue 3 的全域 API 改進

在 Vue 3 中,全域 API 被移到應用實例上,因此每個應用實例可以定義自己的全域配置。例如:

const app = Vue.createApp({});

app.component('local-component', {
  template: '<p>This is a local component</p>'
});

這個元件只在 app 這個應用中有效,不會影響其他應用。


結語

Vue 3 中的 createApp() 引入了應用實例的獨立性,解決了 Vue 2 中共享全域配置導致的潛在問題。

同時,Vue 3 的全域 API 改進讓應用間的耦合性降低,使多應用場景更加靈活。

如果您需要在同一頁面中運行多個 Vue 應用,或希望更細緻地管理全域資源,Vue 3 的 createApp() 是更好的選擇。

Similar Posts