Vue 'emits' 选项
实例
使用 emits 选项来声明从组件发出的自定义事件。
export default {emits: ['custom-event'],methods: {notifyParent() {this.$emit('custom-event','Hello! ')}}}
定义与用法
emits 选项用于记录组件发射的自定义事件。
emits 选项不是必需的,这意味着组件可以发射事件,而无需在 emits 选项中定义它们。
尽管不需要 emits 选项,但仍然建议使用,这样其他程序员就可以轻松地看到组件发射的内容。
当 emits 选项作为一个数组给定时,该数组仅由作为字符串的 emit是 的名称组成。(请参阅上面的实例。)
当 emits 选项作为对象给定时,属性名是 emit 的名称,如果它有一个验证器函数,则该值是验证器函数;如果 emit 没有验证器函数,那么该值为 '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-itemfood-name="Apples"food-desc="Apples are a type of fruit that grow on trees."/><food-itemfood-name="Pizza"/><food-itemfood-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() 方法
Vue 教程: Vue Props
Vue 参考引用: Vue $props 对象
Vue 参考引用: Vue $emit() 方法