為何捐款
API 瀏覽器
提供指令

本指南適用於當您想要建立新的指令並透過 App Extension 提供它時,這會將其注入到託管應用程式中。

提示

若要建立 App Extension 專案資料夾,請先閱讀開發指南 > 簡介

完整範例

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

建立資料夾結構以保持程式碼模組化和有組織。例如,對於指令,建立如下結構

package.json
register-my-directive.js
# 指令的啟動檔案
MyDirective.js
# 指令檔案
index.js
# 在 Index API 中描述

現在,您需要處理註冊 Vue 指令。您可以使用在設定新的 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 Vue directive;
  // "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 生命週期鉤子時呼叫我們的自訂函式。它看起來會像這樣

檔案:/index.js

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

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

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

檔案:/src/boot/my-directive.js

import MyDirective from '../directive/MyDirective.js'

// We globally register our directive with Vue;
// Remember that all directives in Vue will start with 'v-'
// but that should not be part of your directive name
// https://vuejs.org/guide/custom-directive.html#custom-directives
// 'my-directive' will be used as 'v-my-directive'
export default ({ app }) => {
  app.directive('my-directive', MyDirective)
}