vue.js 如何定义app.mount()的返回值类型

oknrviil  于 2023-01-14  发布在  Vue.js
关注(0)|答案(2)|浏览(355)

如何定义app.mount()的返回值类型?
我有一个组件,并希望创建多个应用程序示例,但是当我使用mount()的返回值修改与该组件关联的变量时,ts提示我

Property 'content' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, {}, {}, {}, false, ComponentOptionsBase<any, any, any, any, any, any, any, {}>'

下面是我组件和公开的内容

// myComponent
<template>
hello
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const content = ref('')
defineExpose({ content })
</script>

main.ts中将组件装入dom

// main.ts
import myComponent from './myComponent.vue'
const tooltipInstance = createApp(myComponent).mount('#v-tooltip')
tooltipInstance.content = 'xxx'

此时,ts报告tooltipInstance.conent的错误

Property 'content' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, {}, {}, {}, false, ComponentOptionsBase<any, any, any, any, any, any, any, any, any, {}>>'.ts(2339)

是否有办法获取组件的类型并将其应用于app.mount()的返回值

93ze6v8z

93ze6v8z1#

来自文档:

interface App {
  mount(rootContainer: Element | string): ComponentPublicInstance
}

正如您所看到的,mount方法返回一个ComponentPublicInstance,此外,
对于每个应用示例,mount()只能调用一次。
所以我不认为你能在坐骑方法中做你想做的事情。

0vvn1miw

0vvn1miw2#

虽然编辑器会给出错误提示,但是内容的值是可以获取的,比如我设置为"xxx",可以在控制台打印出来,表示可以获取值,但是在此之前需要在项目根目录下的index.html中设置一个id为v-tooltip的容器来挂载你的示例

// index.html
<div id="v-tooltip"></div>
// myComponent
<template>
hello
</template>
    
<script lang="ts" setup>
import { ref } from 'vue'
const content = ref('Hello World')
defineExpose({ content })
</script>
// main.ts
const app = createApp(myComponent);
const temp = app.mount('v-tooltip')
console.log(temp.content) // The editor will still prompt errors here, 
// but in fact, you have exposed this attribute through the defineExpose method. 
// Expected: output 'Hello World', actual: output 'Hello World'

相关问题