Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a Vue class component with proper types?

If I have a single-file Vue class component, for instance:

// MyComponent.vue
<template>
  <div></div>
</template>

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
})
export default class MyComponent extends Vue {
  public message: string = 'Hello!'
}

And I import it somewhere else, and get an instance of it.

import MyComponent from "./MyComponent.vue";
...
const foo = ... as MyComponent;
foo.message = "goodbye";

With a standard Vue CLI 3 setup this gives an error, because it contains shims-vue.d.ts with the following content:

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

As I understand it, this means that whenever you write import Foo from "./Foo.vue", then Foo will just be an alias for Vue, and you won't be able to access its members.

This does appear to be the case if you import from .ts files. If you import from .vue files, it magically works!

Unfortunately all of my tests are .spec.ts files so I can't import the types of any components. This makes testing difficult. Is there any way to fix this?

like image 606
Timmmm Avatar asked Jan 17 '20 13:01

Timmmm


People also ask

How do I import Vue components?

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.

How do I import a Vue component into JavaScript?

There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.

How do I add a class to Vuejs?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Of course, there is a lot more we can do here with dynamic classes in Vue.


1 Answers

The way I do it in my Vue 2 and Vue 3 projects is as follows:

  1. Create a Foo.vue file and add script tag to the Foo.vue.ts file. Here is snippet.

    <template>
       <div>... Your template code here ...</div>
    </template>
    
    <script lang="ts" src="./Foo.vue.ts" />
    
  2. Write component code in Foo.vue.ts file.

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
})
export default class MyComponent extends Vue {
  public message: string = 'Hello!'
}
  1. Now you can use as keyword.
import MyComponent from "./MyComponent.vue";
...
const foo = obj as MyComponent;
foo.message = "goodbye";
like image 144
Teck Freak Avatar answered Oct 17 '22 18:10

Teck Freak