vue3里如何父子传值
时间: 2023-10-13 19:17:37 浏览: 36
在Vue3中,可以使用props和emit来实现父子组件之间的传值。父组件通过props将数据传递给子组件,子组件可以通过$emit来向父组件发送消息。具体实现方式如下:
父组件:
```
<template>
<div>
<ChildComponent :msg="parentMsg" @childEvent="handleChildEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentMsg: '父组件的数据'
};
},
components: {
ChildComponent
},
methods: {
handleChildEvent(msg) {
console.log(msg); // 子组件传递的消息
}
}
};
</script>
```
子组件:
```
<template>
<div>
{{ msg }}
<button @click="emitEvent">发送消息给父组件</button>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
},
methods: {
emitEvent() {
this.$emit('childEvent', '子组件发送给父组件的消息');
}
}
};
</script>
```
在父组件中,通过将数据绑定到子组件的props上,实现对子组件的传值。通过$emit方法触发的事件,可以在父组件中通过绑定该事件的方法来接收子组件传递的消息。