vue3中父子组件怎么传参 不是vue2
时间: 2023-09-11 16:03:12 浏览: 49
在 Vue 3 中,父组件向子组件传递参数的方式与 Vue 2 有一些不同。以下是在 Vue 3 中传递参数给子组件的方法:
1. 使用 `props` 属性:在子组件中声明需要接收的属性(props),然后在父组件中通过绑定属性的方式将数据传递给子组件。
在子组件中,使用 `props` 选项声明需要接收的属性:
```javascript
// ChildComponent.vue
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
```
在父组件中,通过绑定属性的方式将数据传递给子组件:
```html
<template>
<div>
<child-component :message="parentMessage" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent component'
};
}
}
</script>
```
2. 使用 `v-bind` 缩写:你还可以使用 `v-bind` 缩写将父组件的数据传递给子组件。
在父组件中,使用 `v-bind` 缩写将数据传递给子组件:
```html
<template>
<div>
<child-component v-bind:message="parentMessage" />
</div>
</template>
```
这样,你就可以在 Vue 3 中将数据从父组件传递给子组件。请注意,在 Vue 3 中,`props` 是通过 `v-bind` 或 `:` 进行绑定的,而不是使用 `v-bind:` 的完整写法。