Component passes value (the child page click event changes the parameters of the parent page and is directly triggered)

To directly trigger the methods of the parent page in the click event of the child page, instead of passing parameters through a custom event, you can use the  $parent properties of Vue.js to access the methods of the parent component.

In the parent component:

<template>
  <div>
    <child-component />
    <p>Parent Parameter: {
   
   { parentParameter }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      parentParameter: 'Initial Value'
    };
  },
  methods: {
    updateParentParameter(newValue) {
      this.parentParameter = newValue;
    }
  }
};
</script>

in child component

<template>
  <div>
    <button @click="updateParentParameter('New Value')">Change Parent Parameter</button>
  </div>
</template>

<script>
export default {
  methods: {
    updateParentParameter(newValue) {
      this.$parent.updateParentParameter(newValue);
    }
  }
};
</script>

Methods in parent components  updateParentParameter are used to update parent parameters  parentParameter. The button click event in the child component directly calls  updateParentParameter the method and passes the new value  'New Value' to the parent component.

In the child component, we use  this.$parent the method to access the parent component and call  updateParentParameter the method to trigger the method of the parent component, thereby changing the parameters of the parent component.

In this way, the click event of the child page can directly trigger the method of the parent page without passing parameters through a custom event.

Hope this example helps you! If you have additional questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/m0_38007556/article/details/132875617