vue2父组件调用子方法
时间: 2023-10-16 20:09:25 浏览: 46
在 Vue 2 中,可以通过使用 `ref` 来获取子组件的引用,并调用子组件的方法。下面是一个示例代码:
```vue
<template>
<div>
<child-component ref="child"></child-component>
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
this.$refs.child.childMethod();
}
}
};
</script>
```
在上述代码中,`<child-component>` 是子组件的标签,同时使用了 `ref` 属性来给子组件设置引用名字为 "child"。通过 `this.$refs.child` 可以获取到子组件的引用,然后就可以调用子组件的方法了。在这个例子中,点击按钮时会调用名为 `childMethod()` 的子组件方法。
请注意,为了能够使用 `ref` 引用子组件,子组件需要在父组件中进行导入和注册,如上述代码中的 `import ChildComponent from './ChildComponent.vue'` 和 `components: { ChildComponent }` 部分。