vue2中子组件如何接收父组件的数据
时间: 2023-12-27 19:25:35 浏览: 22
在Vue 2中,子组件可以通过props属性接收父组件传递的数据。以下是一个示例:
父组件:
```vue
<template>
<Child :parentData="parentData" />
</template>
<script>
import Child from "@/components/Child.vue";
export default {
components: {
Child
},
data() {
return {
parentData: "Hello from parent"
};
}
};
</script>
```
子组件:
```vue
<template>
<div>{{ childData }}</div>
</template>
<script>
export default {
props: {
parentData: {
type: String,
required: true
}
},
data() {
return {
childData: ""
};
},
mounted() {
this.childData = this.parentData;
}
};
</script>
```
在上述示例中,父组件通过将`parentData`作为props传递给子组件。子组件通过props属性定义接收的数据类型和是否必需。在子组件中,可以通过`this.parentData`访问父组件传递的数据,并将其赋值给子组件的`childData`属性。在子组件的生命周期函数`mounted`中,可以对接收到的父组件数据进行处理。