vue3 暴露出方法
时间: 2023-12-27 17:24:47 浏览: 40
在Vue3中,可以使用`defineExpose`来暴露组件的方法和属性。通过在子组件中使用`defineExpose`将需要暴露的方法和属性公开,然后在父组件中通过`ref`获取子组件的实例,并使用子组件暴露的方法和属性。
以下是一个示例:
```vue
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref(null);
const callChildMethod = () => {
childRef.value.childMethod();
};
</script>
<script>
import { defineExpose } from 'vue';
export default {
components: {
ChildComponent
},
setup() {
defineExpose({
childMethod() {
console.log('子组件方法被调用');
}
});
}
};
</script>
```
在上面的示例中,父组件通过`ref`获取子组件的实例,并在点击按钮时调用子组件的方法`childMethod`。子组件使用`defineExpose`将`childMethod`暴露出去,以便父组件可以访问和调用。