為何捐款
API 瀏覽器
提供 UI 元件

本指南適用於當您想要建立新的 UI 元件並透過 App Extension 提供時,App Extension 會將其注入到主應用程式中。

提示

為了建立 App Extension 專案資料夾,請先閱讀開發指南 > 介紹

完整範例

若要查看我們將建置的範例,請前往MyComponent 完整範例,這是一個包含此 App Extension 的 GitHub 儲存庫。

建立資料夾結構以保持程式碼模組化和有組織。例如,對於 UI 元件,建立如下所示的結構

package.json
register-my-component.js
# 元件的啟動檔案
MyComponent.vue
# 元件檔案 (可以是 .vue 甚至是 .js)
MyComponent.sass
# 元件的 sass 檔案 (或 .scss/.css,或您需要的任何檔案)
index.js
# 在 Index API 中說明

現在,您需要處理註冊元件。您可以使用在設定新的 App Extension 時建立的 /index.js 檔案 (在 Index API 中說明) 來執行此操作。

讓我們分解一下。

檔案:/index.js

export default function (api) {
  // (Optional!)
  // Quasar compatibility check; you may need
  // hard dependencies, as in a minimum version of the "quasar"
  // package or a minimum version of Quasar App CLI
  api.compatibleWith('quasar', '^2.0.0')

  if (api.hasVite === true) {
    api.compatibleWith('@quasar/app-vite', '^2.0.0-beta.1')
  }
  else { // api.hasWebpack === true
    api.compatibleWith('@quasar/app-webpack', '^4.0.0-beta.1')
  }

  // Here we extend the /quasar.config file, so we can add
  // a boot file which registers our new UI component;
  // "extendConf" will be defined below (keep reading the tutorial)
  api.extendQuasarConf(extendConf)
}

第一組會對 Quasar 進行相容性檢查 (這是選用的,但建議使用)。如果您的元件使用 Quasar 在特定版本之後才提供的功能,您可以確保安裝的 Quasar 版本是正確的版本。

提示

您不僅可以使用 api.compatibleWith() 來檢查 Quasar 套件,還可以檢查任何其他可用的套件 (您自己未透過 App Extension 提供)。請閱讀 App Extension 開發指南 > 介紹頁面中的「處理套件依賴性」章節以取得更多資訊。

第二組告訴 Quasar 在呼叫 extendQuasarConf CLI 生命周期 hook 時呼叫我們的自訂函式。它看起來會像這樣

檔案:/index.js

function extendConf (conf, api) {
  // make sure my-component boot file is registered
  conf.boot.push('~quasar-app-extension-my-component/src/boot/register-my-component.js')

  // @quasar/app-vite does not need this
  if (api.hasVite !== true) {
    // make sure boot & component files get transpiled
    conf.build.transpileDependencies.push(/quasar-app-extension-my-component[\\/]src/)
  }

  // make sure my-component css goes through webpack to avoid ssr issues
  conf.css.push('~quasar-app-extension-my-component/src/component/MyComponent.sass')
}

最後,讓我們看看啟動檔案會是什麼樣子。請確保您先閱讀 @quasar/app-vite 啟動檔案 / @quasar/app-webpack 啟動檔案 文件,並了解什麼是啟動檔案。

檔案:/src/boot/register-my-component.js

import MyComponent from '../component/MyComponent.vue'

// we globally register our component with Vue
export default ({ app }) => {
  app.component('my-component', MyComponent)
}