// 父组件 ParentComponent.vue
<template>
<div>
<ChildComponent ref="childComponent" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
// 使用 this.$refs 来访问子组件实例,并调用其方法
this.$refs.childComponent.childMethod();
}
}
};
</script>
// 子组件 ChildComponent.vue
<template>
<div>
<!-- 子组件内容 -->
</div>
</template>
<script>
export default {
methods: {
childMethod() {
console.log('子组件的方法被调用了');
}
}
};
</script>
ref
属性给子组件起一个引用名(如 childComponent
),然后可以通过 this.$refs.childComponent
访问到子组件的实例。callChildMethod
方法,该方法通过 this.$refs.childComponent.childMethod()
调用子组件中的 childMethod
方法。childMethod
,它会在被父组件调用时执行。上一篇:vue3 全局方法
下一篇:vue 截取字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站