How to modify the value of the parent component with a jetpack?

To modify the value of the parent component, you can achieve this through props and events.

  1. Using props to pass data: in the parent component, pass the value that needs to be modified as props to the child component. The child component can directly access the value in the parent component through props, and can modify this value. When the child component modifies this value, the corresponding data in the parent component will also be modified.
// 父组件
<template>
  <div>
    <ChildComponent :value="parentValue" @updateValue="updateValue" />
    <p>父组件的值: {{ parentValue }}</p>
  </div>
</template>
<script>
  import ChildComponent from './ChildComponent.vue';

  export default {
    data() {
      return {
        parentValue: '初始值',
      };
    },
    methods: {
      updateValue(newValue) {
        this.parentValue = newValue;
      },
    },
    components: {
      ChildComponent,
    },
  };
</script>

// 子组件
<template>
  <div>
    <input v-model="value" @input="updateParentValue" />
    <p>子组件的值: {{ value }}</p>
  </div>
</template>
<script>
  export default {
    props: {
      value: String,
    },
    methods: {
      updateParentValue() {
        this.$emit('updateValue', this.value);
      },
    },
  };
</script>
  1. Usage of events: Define a method in the parent component to modify the value of the parent component, and pass this method to the child component through an event. The child component can then call this method to modify the value of the parent component.
// 父组件
<template>
  <div>
    <ChildComponent @updateValue="updateValue" />
    <p>父组件的值: {{ parentValue }}</p>
  </div>
</template>
<script>
  import ChildComponent from './ChildComponent.vue';

  export default {
    data() {
      return {
        parentValue: '初始值',
      };
    },
    methods: {
      updateValue(newValue) {
        this.parentValue = newValue;
      },
    },
    components: {
      ChildComponent,
    },
  };
</script>

// 子组件
<template>
  <div>
    <button @click="updateParentValue">更新父组件的值</button>
  </div>
</template>
<script>
  export default {
    methods: {
      updateParentValue() {
        this.$emit('updateValue', '新的值');
      },
    },
  };
</script>

The above examples demonstrate two methods to modify the value of the parent component. You can choose one of them based on your actual situation to implement.

bannerAds