父级件:
<template>
<MyLogin ref="MyLoginRef" />
<div @click="hanldClick">按钮</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import MyLogin from './components/MyLogin.vue'
const MyLoginRef = ref<InstanceType<typeof MyLogin> | null>()
const hanldClick = () => {
MyLoginRef.value?.sayHello()
}
</script>
<style scoped></style>
子级件MyLogin.vue:
<template>
<div>我是login</div>
</template>
<script setup lang="ts">
defineExpose({
sayHello: () => {
console.log('sayHello........')
}
})
</script>
<style scoped></style>
其中defineExpose可能会报错:'defineExpose' is not defined.eslint
Vue <script setup> compiler macro for declaring a component's exposed instance properties when it is accessed by a parent component via template refs.
<script setup> components are closed by default - i.e. variables inside the <script setup> scope is not exposed to parent unless explicitly exposed via defineExpose.
This is only usable inside <script setup>, is compiled away in the output and should not be actually called at runtime.
处理方法:.eslintrc.js