"Back end partners are coming to the pre-school" Vue components bind custom events to realize communication

Keywords: Front-end Vue.js Back-end


Evening moon

preface

Originally, I intended to write the principle of the global event bus in Vue, but I found that I wrote less about the custom event, did not understand the operation of the custom event, and it was difficult to write the principle of the global event, so I had this article.

1, v-on instruction

To talk about custom events, you must first talk about the v-on instruction. Because v-on is the basis of implementing custom events.

v-on official website documents

Basic introduction

The v-on instruction can be abbreviated to @, and when we use the v-on instruction, it actually has a default parameter event

There are several modifiers that can be matched with it:

  1. . stop - call event.stopPropagation(). Stop bubbling
  2. . prevent - call event.preventDefault(). Block default behavior
  3. . capture - use capture mode when adding event listeners.
  4. . self - the callback is triggered only when the event is triggered from the listener bound element itself.
  5. . {keyCode | keyAlias} - the callback is triggered only when the event is triggered from a specific key. Key modifier, key alias
  6. . native - listens for native events of the component root element.
  7. . once - only one callback is triggered.
  8. . left - (2.2.0) triggered only when the left mouse button is clicked.
  9. . right - (2.2.0) triggered only when the right mouse button is clicked.
  10. . middle - (2.2.0) triggered only when the middle mouse button is clicked.
  11. . passive - (2.3.0) add listener in {passive: true} mode

These modifier parts can be used in series.

effect:

  • Bind event listener. The event type is specified by the parameter. An expression can be the name of a method or an inline statement, or it can be omitted without modifiers.

  • When used on ordinary elements, you can only listen for native DOM events. When used on a custom element component, you can also listen for custom events triggered by child components.

    Today's second point is our focus.

Example:

<!-- Method processor -->
<button v-on:click="doThis"></button>

<!-- Dynamic events (2.6.0+) -->
<button v-on:[event]="doThis"></button>

<!-- Inline statement -->
<button v-on:click="doThat('hello', $event)"></button>

<!-- abbreviation -->
<button @click="doThis"></button>

<!-- Dynamic event abbreviation (2.6.0+) -->
<button @[event]="doThis"></button>

<!-- Stop bubbling -->
<button @click.stop="doThis"></button>

<!-- Block default behavior -->
<button @click.prevent="doThis"></button>

<!-- Block default behavior, no expression -->
<form @submit.prevent></form>

<!--  Concatenation modifier -->
<button @click.stop.prevent="doThis"></button>

<!-- Key modifier, key alias -->
<input @keyup.enter="onEnter">

<!-- Key modifier, key code -->
<input @keyup.13="onEnter">

<!-- Clicking callback will only trigger once -->
<button v-on:click.once="doThis"></button>

<!-- Object syntax (2.4.0+) -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

Listen for custom events on the subcomponent (the event handler will be called when the subcomponent triggers "my event"):

<my-component @my-event="handleThis"></my-component>

<!-- Inline statement -->
<my-component @my-event="handleThis(123, $event)"></my-component>

<!-- Native events in components -->
<my-component @click.native="onClick"></my-component>

After reading this v-on, I wonder if you remember $on on the VueComponent instance, that is, vm.$on(event,callback).

  • vm.$on(event,callback) usage:

    Listen for custom events on the current instance. Events can be triggered by vm.$emit. The callback function receives additional parameters for all incoming event trigger functions.

Here, I suggest you think about their differences, because vm.$on is actually the principle of implementing the global event bus.

2, Custom event

Simple illustration:

We bind A custom event to component A through v-on or @ in the App component. Its trigger time is to wait until component A calls this.$emit('myevent ') internally, and then trigger the callback in the App component.

In fact, we bind a custom event to component a through v-on. Its essence is that we bind an event on the instance object VC of component A, and the event name is our custom name.

Because we wrote a < a > < / a > component tag, the Vue bottom layer also wants to help us with the new VueComponent() object.

About customizing event names

Custom event names are different from components and prop s. There is no automatic case conversion for event names. You can listen to this event only if the event name exactly matches.

The v-on event listener will be automatically converted to all lowercase in the DOM template, so v-on:myEvent will become v-on: my event, making it impossible for myEvent to be listened to.

vue always recommends that you always use the event name of kebab case.

3, Introductory case

Realization effect

App components

<template>
  <div id="app">
    <!-- props Method transfer -->
    <Demo :showMsg="showMsg"></Demo>
    <!--Binding custom events send-message:Is our custom event name, followed by sendMessage Callback function that the custom event is triggered to execute -->
    <Demo1 v-on:send-message="sendMessage"></Demo1>
  </div>
</template>

<script>
import Demo from "./components/Demo.vue";
import Demo1 from "./components/Demo1.vue";

export default {
  name: "App",
  components: {
    Demo,
    Demo1,
  },
  methods: {
    showMsg() {
      alert("Received from demo Information about");
    },
    sendMessage(value) {
      alert("sendMessage Custom event triggered!!! Received from demo2 Information about:" + value);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Demo component

<template>
  <div class="demo">
    <h1>Demo</h1>
    <p>{{ msg }}</p>
    <button type="button" @click="sendMsg">Click send message to App assembly</button>
  </div>
</template>
<script>
export default {
  props: {
    showMsg: Function,
  },
  data() {
    return {
      msg: "hello,hello everyone,I'm Ning in spring",
    };
  },
  methods: {
    sendMsg() {
      this.showMsg();
    },
  },
};
</script>
<style>
.demo {
  width: 200px;
  height: 200px;
  background-color: #1488f5;
}
</style>

demo1

<template>
  <div class="demo1">
    <h1>Demo2</h1>
    <span>{{ msg }}</span>

    <button @click="sendAppMsg(msg)" type="button">
      Click send message to App assembly
    </button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: "Hello, I'm from Demo2 Better in spring",
    };
  },
  methods: {
    sendAppMsg(message) {
      this.$emit("send-message", message);
    },
  },
};
</script>
<style>
.demo1 {
  width: 200px;
  height: 200px;
  background-color: pink;
}
</style>

Today is to write a header, and the next section will talk about the principle of global event bus.

Post language

Let's cheer together!!! If there are any deficiencies in the article, please point out them in time. Thank you very much.

I feel shallow on paper. I absolutely know that I have to practice it.

Hello, I'm blogger Ning Zaichun: homepage

A young man who likes literature and art but embarks on the road of programming.

Hope: when we meet on another day, we have achieved something.

Posted by anoopmail on Thu, 18 Nov 2021 18:00:56 -0800