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?
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.
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.
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.
The way I do it in my Vue 2 and Vue 3 projects is as follows:
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" />
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!'
}
as
keyword.import MyComponent from "./MyComponent.vue";
...
const foo = obj as MyComponent;
foo.message = "goodbye";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With