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 教程:作用域样式