選項:其他
name
顯式宣告元件的顯示名稱。
型別
tsinterface ComponentOptions { name?: string }
詳細資訊
元件名稱用於以下情況:
- 元件自身模板中的遞迴自引用
- 在 Vue DevTools 的元件檢查樹中顯示
- 在警告元件跟蹤中顯示
當使用單檔案元件時,元件會從檔名中推斷其名稱。例如,名為
MyComponent.vue
的檔案將具有推斷的顯示名稱 "MyComponent"。另一個情況是,當元件透過
app.component
全域性註冊時,全域性 ID 將自動設定為它的名稱。name
選項允許您覆蓋推斷的名稱,或者在沒有名稱可以推斷時(例如,不使用構建工具或內聯非 SFC 元件)顯式提供名稱。有一種情況下,
name
是必須顯式指定的:當透過<KeepAlive>
的include / exclude
屬性匹配可快取的元件時。提示
自 3.2.34 版本以來,使用
<script setup>
的單檔案元件將自動根據檔名推斷其name
選項,即使與<KeepAlive>
一起使用,也不需要手動宣告名稱。
inheritAttrs
控制是否啟用預設元件屬性穿透行為。
型別
tsinterface ComponentOptions { inheritAttrs?: boolean // default: true }
詳細資訊
預設情況下,未被識別為props的父作用域屬性繫結會“穿透”。這意味著當只有一個根元件時,這些繫結將作為正常HTML屬性應用於子元件的根元素。當編寫一個包裹目標元素或另一個元件的元件時,這不一定是我們期望的行為。透過將
inheritAttrs
設定為false
,可以停用這種預設行為。屬性可以透過$attrs
例項屬性訪問,並且可以使用v-bind
顯式繫結到非根元素。示例
當在一個使用
<script setup>
的元件中宣告此選項時,可以使用defineOptions
宏。vue<script setup> defineProps(['label', 'value']) defineEmits(['input']) defineOptions({ inheritAttrs: false }) </script> <template> <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on:input="$emit('input', $event.target.value)" /> </label> </template>
另請參閱
元件
一個物件,用於註冊要供元件例項使用的元件。
型別
tsinterface ComponentOptions { components?: { [key: string]: Component } }
示例
jsimport Foo from './Foo.vue' import Bar from './Bar.vue' export default { components: { // shorthand Foo, // register under a different name RenamedBar: Bar } }
另請參閱 元件註冊
指令
一個物件,用於註冊要供元件例項使用的指令。
型別
tsinterface ComponentOptions { directives?: { [key: string]: Directive } }
示例
jsexport default { directives: { // enables v-focus in template focus: { mounted(el) { el.focus() } } } }
模板<input v-focus>
另請參閱 自定義指令