vue中父组件如何调用子组件的方法
在vue中,父组件可以通过$refs来访问子组件,并调用子组件的方法。
示例代码:
子组件:
<template>
<div>
<button @click="showMessage">显示消息</button>
</div>
</template>
<script>
export default {
methods: {
showMessage() {
console.log('Hello World');
}
}
}
</script>
父组件:
<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.showMessage();
}
}
}
</script>
在父组件中,我们通过$refs访问了子组件,并调用了子组件的showMessage方法。注意,我们需要给子组件设置ref属性,这样才能在父组件中访问到子组件
原文地址: http://www.cveoy.top/t/topic/epin 著作权归作者所有。请勿转载和采集!