Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type vue instance out of `defineComponent()` in vue 3?

As you know, as of Vue 3, component could be written in TypeScript:

/// modal.vue

<template>
  <div class="modal"></div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Modal",
  props: {
    foo: String,
    bar: String
  },
  mounted() {
    this.$props.foo // how to type `this` out of this context?
  }
});
</script>

My question is how can I type the vue instance out of the defineComponent function?

/// another ts file.
let modal:???; // what the `???` should be?

modal.$props.foo // infer `$props.foo` correctly
like image 476
yaquawa Avatar asked Sep 21 '20 03:09

yaquawa


People also ask

What is defineComponent in vue3?

defineComponent({ setup: function , name: 'some name' }); As you see, all these cases are responsible for different scenarios, yet the return type is always the same: a defineComponent interface with all the types you need to apply for the props, data and the other settings that are needed for the component.

How do I switch between Vue components?

You need to bind the value into the component and then emit a new value to the parent when you click a link. If you emit the event input and bind the value value , then you can use v-model .


Video Answer


1 Answers

The "simple" answer I was going to give was to use ReturnType<typeof defineComponent> however that doesn't carry any of the type information. As I started to look at how ReturnType could be used with a generic method I fell down stackoverflow rabbit hole where these seemed like something to explore

However after looking at it, vue has an exported type ComponentPublicInstance that can be used fairly easily. ComponentPublicInstance also has handful of different generic parameters.

import { ComponentPublicInstance } from 'vue';

let instance: ComponentPublicInstance<{ prop: string }, { value: string }>;
like image 159
David Driscoll Avatar answered Sep 22 '22 17:09

David Driscoll