Vue $emit() 方法
示例
使用 $emit()
方法在點選按鈕時觸發自定義事件到父元件。
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Click the button to trigger the custom event up to the parent component using the $emit() method.</p>
<button v-on:click="this.$emit('custom-event')">Trigger</button>
</div>
</template>
執行示例 »
更多示例請參見下方。
定義和用法
內建的 $emit()
方法會觸發一個自定義事件,用於向上與父元件通訊。
引數 | 描述 |
---|---|
自定義事件名稱 | 預設。第一個引數是使用 $emit() 方法觸發的自定義事件的名稱。 |
更多引數 | 可選。可以使用一個或多個引數作為載荷與自定義事件一起傳送。(請參見下面的示例 1 和 2。) |
emits
選項 可用於記錄元件發出的內容。使用 emits
選項可以提高可讀性,但它不是必需的。(請參見下面的示例 3。)
Props 用於在相反的方向通訊:從父元件向下到子元件。在教程中瞭解更多關於 props 的資訊。
更多示例
示例 1
使用 $emit()
方法傳送訊息到父元件,使用 'message-sent' 自定義事件。
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Write something, and send the message up to the parent component using the $emit() method.</p>
<input type="text" v-model="message" placeholder="write something..">
<button v-on:click="send">Send</button>
</div>
</template>
<script>
export default {
data() {
return {
message: null
}
},
methods: {
send() {
this.$emit('message-sent',this.message);
}
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
input {
display: block;
margin-bottom: 15px;
}
</style>
執行示例 »
示例 2
使用 $emit()
方法將產品名稱和評分發送到父元件。
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Rate a product:</p>
<input type="text" v-model="productName" placeholder="Product name.." ref="inpName">
<input type="number" v-model="productRating" placeholder="Rating 1 to 10..">
<button v-on:click="send">Register</button>
</div>
</template>
<script>
export default {
data() {
return {
productName: null,
productRating: null
}
},
methods: {
send() {
this.$emit('message-sent',this.productName,this.productRating);
this.productName = null;
this.productRating = null;
this.$refs.inpName.focus();
}
},
mounted() {
this.$refs.inpName.focus();
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
input {
display: block;
margin-bottom: 15px;
}
</style>
執行示例 »
示例 3
使用 emits
選項使用 $emit()
方法記錄元件發出的內容。這不是必需的,但可以提高可讀性。
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Click the button to trigger the custom event up to the parent component using the $emit() method.</p>
<button v-on:click="this.$emit('custom-event')">Trigger</button>
</div>
</template>
<script>
export default {
emits: ['custom-event']
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
</style>
執行示例 »
相關頁面
Vue 教程:Vue $emit() Method
Vue 教程:Vue Props
Vue 教程:Vue 事件
Vue 教程: Vue v-on 指令
Vue 教程:作用域樣式