Vue 'emits' 选项

实例

使用 emits 选项来声明从组件发出的自定义事件。

  1. export default {
  2. emits: ['custom-event'],
  3. methods: {
  4. notifyParent() {
  5. this.$emit('custom-event','Hello! ')
  6. }
  7. }
  8. }

定义与用法

emits 选项用于记录组件发射的自定义事件。

emits 选项不是必需的,这意味着组件可以发射事件,而无需在 emits 选项中定义它们。

尽管不需要 emits 选项,但仍然建议使用,这样其他程序员就可以轻松地看到组件发射的内容。

emits 选项作为一个数组给定时,该数组仅由作为字符串的 emit是 的名称组成。(请参阅上面的实例。)

emits 选项作为对象给定时,属性名是 emit 的名称,如果它有一个验证器函数,则该值是验证器函数;如果 emit 没有验证器函数,那么该值为 'null'。(请参阅下面的实例。)


更多实例

实例

使用 props 作为带有选项的对象,以便在父组件未提供默认食物描述时显示该描述。

FoodItem.vue:

  1. <template>
  2. <div>
  3. <h2>{{ foodName }}</h2>
  4. <p>{{ foodDesc }}</p>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. props: {
  10. foodName: {
  11. type: String,
  12. required: true
  13. },
  14. foodDesc: {
  15. type: String,
  16. required: false,
  17. default: 'This is the food description...'
  18. }
  19. }
  20. };
  21. </script>

App.vue:

  1. <template>
  2. <h1>Food</h1>
  3. <p>Food description is not provided for 'Pizza' and 'Rice', so the default description is used.</p>
  4. <div id="wrapper">
  5. <food-item
  6. food-name="Apples"
  7. food-desc="Apples are a type of fruit that grow on trees."/>
  8. <food-item
  9. food-name="Pizza"/>
  10. <food-item
  11. food-name="Rice"/>
  12. </div>
  13. </template>
  14. <style>
  15. #wrapper {
  16. display: flex;
  17. flex-wrap: wrap;
  18. }
  19. #wrapper > div {
  20. border: dashed black 1px;
  21. flex-basis: 120px;
  22. margin: 10px;
  23. padding: 10px;
  24. background-color: lightgreen;
  25. }
  26. </style>

关联页面

Vue 教程: Vue $emit() 方法

Vue 教程: Vue Props

Vue 参考引用: Vue $props 对象

Vue 参考引用: Vue $emit() 方法

分类导航