vue3 vite 父组件调用子组件的方法
在Vue 3中,可以通过ref和setup函数来实现父组件调用子组件的方法。
首先,你需要在子组件中创建一个ref,并将需要暴露给父组件的方法设置为ref的属性。然后,在父组件中使用ref引用子组件实例,并通过.value属性来访问子组件的方法。
以下是一个示例:
子组件:
<template>
<div>
<button @click="childMethod">子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const childMethod = () => {
console.log('子组件方法被调用');
};
return {
childMethod: ref(childMethod)
};
}
};
</script>
父组件:
<template>
<div>
<button @click="callChildMethod">调用子组件方法</button>
<ChildComponent ref="childRef" />
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
this.$refs.childRef.childMethod.value(); // 调用子组件方法
}
}
};
</script>
在父组件中,我们使用ref来引用子组件实例,并使用this.$refs.childRef.childMethod.value()来调用子组件的方法。
需要注意的是,在Vue 3中,ref返回的是一个包装对象,所以我们需要使用.value来访问被包装的值。
希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/jcgn 著作权归作者所有。请勿转载和采集!