[Vue] The child component calls the method of the parent component - case

Ok, here's a simple case:

Parent component Parent.vue:

<template>
  <div>
    <h2>Parent Component</h2>
    <child-component @text-updated="updateText"/>
    <p>Text from child component: {
   
   { childText }}</p>
  </div>
</template>

<script>
import ChildComponent from './Child.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      childText: ''
    }
  },
  methods: {
    updateText(text) {
      this.childText = text;
    }
  }
}
</script>

Child component Child.vue:

<template>
  <div>
    <h2>Child Component</h2>
    <button @click="updateParentText()">Update Parent Text</button>
  </div>
</template>

<script>
export default {
  methods: {
    updateParentText() {
      this.$emit('text-updated', 'Text updated from child component');
    }
  }
}
</script>
In this case, the child component  $emit sends a custom event to the parent component by calling the method  text-updated, and passes a string parameter to update the data in the parent component  childText , so that the child component calls the method of the parent component. In the parent component, we listened to  text-updated the event and  updateText defined its corresponding processing method in the parent component. When the child component calls  $emit the method, the method will be automatically triggered to update the data in the parent component.

Guess you like

Origin blog.csdn.net/weixin_45481821/article/details/131711551