Detailed explanation of the event of triggering a child component by clicking a button in the parent component in vue

  • 2021-09-20 19:13:02
  • OfStack

I divide this example into several steps to interpret:

1. The button element of the parent component binds an click event that points to the notify method
2. Register 1 ref = "child" for subcomponents
3. The notify method of the parent component uses $refs. child to pass the event to the parentMsg method of the child component, and carries the parameter msg of the parent component at the same time
4. After the child component receives the event of the parent component, it calls the parentMsg method and puts the received msg into the message array

Parent component


<template>
 <div id="app">
  <!-- Parent component -->
  <input v-model="msg" />
  <button v-on:click="notify"> Broadcast event </button>
  <!-- Subcomponent -->
  <popup ref="child"></popup>
 </div>
</template>
 <script>
import popup from "@/components/popup";
export default {
 name: "app",
 data: function () {
  return {
   msg: "",
  };
 },
 components: {
  popup,
 },
 methods: {
  notify: function () {
   if (this.msg.trim()) {
    this.$refs.child.parentMsg(this.msg);
   }
  },
 },
};
</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>

Subcomponent


<template>
 <div>
  <ul>
   <li v-for="item in messages"> The parent component entered: {{ item }}</li>
  </ul>
 </div>
</template>
 <style>
body {
 background-color: #ffffff;
}
</style>
 <script>
export default {
 name: "popup",
 data: function () {
  return {
   messages: [],
  };
 },
 methods: {
  parentMsg: function (msg) {
   this.messages.push(msg);
  },
 },
};
</script>

Related articles: