在 Vue 中,父组件可以通过 ref
来获取子组件实例,并通过实例调用子组件的方法。
在父组件中,可以给子组件添加一个 ref
属性:
<template>
<child ref="childComponent"></child>
</template>
然后在父组件的方法中调用子组件的方法:
export default {
methods: {
callChildMethod() {
this.$refs.childComponent.childMethod();
}
}
}
在子组件中,需要定义 childMethod()
方法:
export default {
methods: {
childMethod() {
console.log('child method is called');
}
}
}
这样父组件就可以通过 ref
属性调用子组件的方法了。