Vue 'emits' 選項
示例
使用 emits
選項宣告元件發出的自定義事件。
export default {
emits: ['custom-event'],
methods: {
notifyParent() {
this.$emit('custom-event','Hello! ')
}
}
}
執行示例 »
檢視下面的更多示例
定義和用法
emits
選項用於記錄元件發出的自定義事件。
emits
選項不是必需的,這意味著元件可以在不定義 emits
選項的情況下發出事件。
儘管 emits
選項不是必需的,但仍然建議使用它,以便其他程式設計師可以輕鬆地看到元件發出的內容。
當 emits
選項以陣列形式給出時,陣列僅包含發出事件的名稱作為字串。(參見上面的示例。)
當 emits
選項以物件形式給出時,屬性名稱是發出事件的名稱,值是驗證器函式(如果存在),或者在沒有驗證器函式時為 'null'。(參見下面的示例。)
更多示例
示例
使用具有選項的物件作為 props,以便在父元件未提供時顯示預設的食物描述。
FoodItem.vue
:
<template>
<div>
<h2>{{ foodName }}</h2>
<p>{{ foodDesc }}</p>
</div>
</template>
<script>
export default {
props: {
foodName: {
type: String,
required: true
},
foodDesc: {
type: String,
required: false,
default: 'This is the food description...'
}
}
};
</script>
App.vue
:
<template>
<h1>Food</h1>
<p>Food description is not provided for 'Pizza' and 'Rice', so the default description is used.</p>
<div id="wrapper">
<food-item
food-name="Apples"
food-desc="Apples are a type of fruit that grow on trees."/>
<food-item
food-name="Pizza"/>
<food-item
food-name="Rice"/>
</div>
</template>
<style>
#wrapper {
display: flex;
flex-wrap: wrap;
}
#wrapper > div {
border: dashed black 1px;
flex-basis: 120px;
margin: 10px;
padding: 10px;
background-color: lightgreen;
}
</style>
執行示例 »
相關頁面
Vue 教程:Vue $emit() Method
Vue 教程:Vue Props
Vue Reference: Vue $props Object
Vue Reference: Vue $emit() Method