Home > Software engineering >  how to define the return value type of app.mount()
how to define the return value type of app.mount()

Time:01-11

how to define the return value type of app.mount()

I have a component and want to create Multiple application instances, but when I use the return value of the mount() to modify the variables associated with the component, ts prompts me that

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

here is my component, and expose content

// myComponent
<template>
hello
</template>

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

mount component to dom in main.ts

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

At this time, ts reports an error for tooltipInstance.conent

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

Is there any way to get the type of component and apply it to the return value of app.mount()

CodePudding user response:

From the documentation:

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

As you can see the mount method returns a ComponentPublicInstance and furthermore,

For each app instance, mount() can only be called once.

So I do not think you can do what you desire in the mount method.

CodePudding user response:

Although the editor will give an error prompt, the value of content can be obtained. For example, I set it to 'xxx', which can be printed on the console, which means that the value can be obtained. But before that, you need to set a container with the id of v-tooltip in index.html under the project root directory to mount your instance

// 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'
  • Related