Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This is the ninth article in this series on Fragments and emits

Previous related articles can be moved:

  • Vue series: Vue3’s new composition API
  • The use of ref and Reactive functions in composition API in Vue3
  • [Vue series-3] About responsive deep listening and non-deep listening
  • [Vue3 series -4] toRaw and markRaw in Composition API
  • Do you know ref as well as toRef and toRefs
  • You may know ref, but do you know how to customize a ref
  • Do you know how to get DOM elements from the ref attribute in Vue3
  • [Vue3 series -8] About the use of portal components in Vue3

Vue3 components can have multiple roots

We know that in vue2. X, each component can have only one root, which means that we write each component template with a parent element. Vue3 has introduced Fragments to make it easier to write component templates, which means that components in VUe3 can have multiple roots

For example, by creating a fragments.vue, the component template can write multiple roots

<template>
    <div>
        <h1>Fragments</h1>
    </div>
    <div>
        <p>Vue3 introduces Fragments, meaning Fragments</p>
        <p>In other words, vuE3 components can have multiple roots</p>
    </div><! -- You can have more roots --> </template>Copy the code

As above, the change from single roots to multiple roots is not a bit Fragmens, which is where the meaning of Fragmens comes from —-

Vue3 adds the emits option for custom events

Vue3 added the emits option. User-defined events sent by components must be defined in the emits option. One is to avoid situations where custom events fire multiple times when they have the same name as native events, such as the Click event. Second, it gives a better indication of how components work

For example, to create a Emits. Vue, we customize a click event

<template>
  <button @click="$emit('click')">Am I</button>
</template>
<script>
export default {
    //emits:['click']
};
</script>
Copy the code

If the custom event is not written to the emits option, the event will be fired multiple times when the custom event name conflicts with the native event name

<template>
  <Emits @click="onClick"></Emits>
</template>

<script>
import Emits from './components/Emits.vue'
export default {
  name: 'App'.components: {
    Emits
  },
  methods: {onClick(){console.log('clicked!!!!! ')}}}</script>
Copy the code

Therefore, when vue3 writes custom events, it is recommended to write custom events in the emits option