Vue3 子组件修改父组件的值:v-model 指令与 emit 事件
在 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 上,这样就能实现子组件修改父组件的值了。
原文地址: https://www.cveoy.top/t/topic/mBrH 著作权归作者所有。请勿转载和采集!