vue3怎么父子传参
时间: 2023-08-14 10:10:24 浏览: 46
在Vue 3中,父子组件之间的参数传递可以通过属性传递和事件传递来实现。
1. 属性传递(Props):父组件通过在子组件上绑定属性的方式传递数据,子组件通过props选项来接收父组件传递的数据。
父组件模板中:
```html
<template>
<ChildComponent :message="parentMessage"></ChildComponent>
</template>
```
父组件中的数据:
```javascript
export default {
data() {
return {
parentMessage: 'Hello from parent component'
};
}
}
```
子组件中的props接收:
```javascript
export default {
props: ['message'],
// 或者使用props选项
// props: {
// message: String
// },
// ...
}
```
2. 事件传递(Event):子组件通过$emit方法触发一个自定义事件,父组件通过在子组件上监听该事件来接收数据。
子组件中触发事件:
```javascript
export default {
methods: {
handleClick() {
this.$emit('childEvent', 'Data from child component');
}
}
}
```
父组件中监听事件:
```html
<template>
<ChildComponent @childEvent="handleChildEvent"></ChildComponent>
</template>
```
父组件中的方法:
```javascript
export default {
methods: {
handleChildEvent(data) {
console.log(data); // 输出:Data from child component
}
}
}
```
通过以上两种方式,你可以在Vue 3中实现父子组件之间的参数传递。