vue3获取ref实例ts怎么写

父级件:

<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


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容