vue获取子组件数据
时间: 2023-08-18 21:11:33 浏览: 46
在 Vue 中,可以通过使用 `ref` 来获取子组件的数据。以下是一个示例:
在父组件中,使用 `ref` 来引用子组件,并通过 `$refs` 来访问子组件的数据和方法。
```html
<template>
<div>
<child-component ref="child"></child-component>
<button @click="getChildData">获取子组件数据</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
getChildData() {
const childData = this.$refs.child.childData;
console.log(childData);
}
}
};
</script>
```
在子组件中,通过 `props` 将数据传递给父组件,并在需要传递的数据上使用 `this.$emit` 方法。
```html
<template>
<div>
<!-- 子组件模板 -->
</div>
</template>
<script>
export default {
data() {
return {
childData: '子组件数据'
};
}
};
</script>
```
在上述示例中,父组件通过 `ref` 引用了子组件,并在点击按钮时调用 `getChildData` 方法。该方法通过 `this.$refs.child` 访问到子组件实例,并获取子组件的 `childData` 数据。
请注意,使用 `$refs` 来访问子组件的数据需要在子组件渲染完成后才能正常访问。