<template>
<div>
<child-component ref="childComponent"></child-component>
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const childComponent = ref(null);
const callChildMethod = () => {
if (childComponent.value) {
childComponent.value.childMethod();
}
};
return {
childComponent,
callChildMethod
};
}
};
</script>
模板部分 (<template>):
<child-component ref="childComponent"></child-component> 来引入子组件,并通过 ref 属性为子组件创建一个引用。callChildMethod 方法。脚本部分 (<script>):
ref 和子组件 ChildComponent。setup 函数中定义 childComponent 引用和 callChildMethod 方法。callChildMethod 方法检查子组件是否已挂载,然后调用子组件的 childMethod 方法。子组件 (ChildComponent.vue):
childMethod 的方法,可以在其 <script> 部分定义:export default {
methods: {
childMethod() {
console.log('子组件方法被调用了');
}
}
};
这样,当点击按钮时,父组件会调用子组件中的 childMethod 方法。
上一篇:vue json 编辑器
下一篇:vue获取时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站