vue3 子组件修改父组件值
时间: 2023-09-18 12:09:48 浏览: 79
在Vue 3中,子组件要修改父组件的值,可以通过事件触发的方式实现。
首先,在父组件中定义一个数据,并通过props将它传递给子组件:
```vue
<template>
<div>
<p>父组件的值:{{ parentValue }}</p>
<child-component :childValue="parentValue" @update-value="updateParentValue"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentValue: '初始值'
}
},
methods: {
updateParentValue(newValue) {
this.parentValue = newValue;
}
}
}
</script>
```
然后,在子组件中使用props接收父组件传递的值,并通过$emit方法触发一个自定义事件,将修改后的值传递给父组件:
```vue
<template>
<div>
<p>子组件的值:{{ childValue }}</p>
<button @click="updateValue">修改父组件的值</button>
</div>
</template>
<script>
export default {
props: ['childValue'],
methods: {
updateValue() {
const newValue = '新的值';
this.$emit('update-value', newValue);
}
}
}
</script>
```
在子组件中,当点击按钮时,会调用`updateValue`方法,修改父组件的值并通过`$emit`触发名为`update-value`的事件,并传递新的值给父组件。
在父组件中,通过监听`update-value`事件,调用`updateParentValue`方法来更新父组件的值。
这样,当子组件点击按钮并触发事件时,父组件的值会被更新。