在Vue3中,子组件修改父组件的值需要使用v-model指令配合emit事件来实现。

首先,在父组件中将需要修改的值作为props传递给子组件,并将该值绑定到v-model指令上。然后在子组件中,通过$emit方法触发一个自定义事件,并将修改后的值作为参数传递给父组件。

父组件代码:

<template>
  <div>
    <ChildComponent v-model="parentValue" />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data () {
    return {
      parentValue: ''
    }
  }
}
</script>

子组件代码:

<template>
  <div>
    <input type="text" v-model="childValue" @input="updateParentValue" />
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      childValue: this.value
    }
  },
  methods: {
    updateParentValue () {
      this.$emit('input', this.childValue)
    }
  }
}
</script>

在子组件中,我们通过props接收父组件传递的value值,并将其赋值给子组件的data中的childValue。然后我们在子组件的input事件中调用updateParentValue方法,该方法通过$emit方法触发一个名为input的自定义事件,并将childValue作为参数传递给父组件。

最后,我们在父组件中将ChildComponent组件的v-model绑定到parentValue上,这样就能实现子组件修改父组件的值了。

vue3 子组件修改父组件的值

原文地址: https://www.cveoy.top/t/topic/bbdd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录