自定義元素 API
defineCustomElement()
此方法接受與 defineComponent
相同的引數,但返回一個原生的 自定義元素 類建構函式。
型別
tsfunction defineCustomElement( component: | (ComponentOptions & CustomElementsOptions) | ComponentOptions['setup'], options?: CustomElementsOptions ): { new (props?: object): HTMLElement } interface CustomElementsOptions { styles?: string[] // the following options are 3.5+ configureApp?: (app: App) => void shadowRoot?: boolean nonce?: string }
型別已簡化以提高可讀性。
詳情
除了正常的元件選項外,
defineCustomElement()
還支援一些特定於自定義元素的選項styles
:一組內聯 CSS 字串陣列,用於提供應注入元素影子的 CSS。configureApp
:一個函式,可用於為自定義元素配置 Vue 應用程式例項。shadowRoot
:布林值
,預設為true
。設定為false
以在沒有影子根的情況下渲染自定義元素。這意味著自定義元素 SFC 中的<style>
將不再被封裝。nonce
:string
,如果提供,將被設定為注入到影子根中的樣式標籤的nonce
屬性。
注意,這些選項不僅可以作為元件的一部分傳遞,還可以透過第二個引數傳遞。
jsimport Element from './MyElement.ce.vue' defineCustomElement(Element, { configureApp(app) { // ... } })
返回值是一個自定義元素建構函式,可以使用
customElements.define()
進行註冊。示例
jsimport { defineCustomElement } from 'vue' const MyVueElement = defineCustomElement({ /* component options */ }) // Register the custom element. customElements.define('my-vue-element', MyVueElement)
另請參閱
此外,請注意,當與單檔案元件一起使用時,
defineCustomElement()
需要特殊配置。
useHost()
一個組合式API助手,返回當前Vue自定義元素的宿主元素。
useShadowRoot()
一個組合式API助手,返回當前Vue自定義元素的影子根。
this.$host
一個選項API屬性,用於公開當前Vue自定義元素的宿主元素。