// 父组件调用子组件方法的示例代码
// 子组件 ChildComponent.vue
<template>
<div>
<p>这是子组件</p>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
methods: {
childMethod() {
console.log('子组件的方法被调用了');
}
}
}
</script>
// 父组件 ParentComponent.vue
<template>
<div>
<p>这是父组件</p>
<ChildComponent ref="childComponent" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
methods: {
callChildMethod() {
this.$refs.childComponent.childMethod(); // 通过 ref 调用子组件的方法
}
}
}
</script>
子组件 (ChildComponent.vue
):
childMethod
的方法。这个方法会在控制台打印一条消息。父组件 (ParentComponent.vue
):
ref
属性为子组件指定了一个引用名称(ref="childComponent"
)。callChildMethod
方法。callChildMethod
方法通过 this.$refs.childComponent.childMethod()
调用了子组件中的 childMethod
方法。通过这种方式,父组件可以成功调用子组件中的方法。
上一篇:vue :style
下一篇:vue3 setup
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站