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() 方法触发一个自定义事件,该事件用于与父组件进行通信。
| 参数 | 描述 |
|---|---|
| Custom event name | 默认。第一个参数是用 $emit() 方法触发的自定义事件的名称 |
| More arguments | 可选。一个或多个参数可以与自定义事件一起作为 payload(有效载荷)发送(参见下面的实例1和2。) |
Emits 选项可用于记录组件发送的内容。使用 emits 选项可以提高可读性,但这不是必需的。(参见下面的实例3。)
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>