1
votes

I am using vue-class-component so that I can use class syntax and typescript type checking in .vue files. I can create .vue files and register them as components with this syntax, except for the root Vue() instance.

This works

The hello.vue file looks like this, it's using vue-class-component (shortened for brevity)

<template></template>

<script lang="ts">
    import Vue from 'vue'
    import Component from 'vue-class-component'
    @Component({
    })
    export default class Hello extends Vue {
        created() {
            console.log("I am created!")
        }
    }
</script>

Now, I can import hello in the root vue instance like this:

import Hello from "./components/hello.vue"

let v = new Vue({
    el: "#app",
    template: `<div><hello></hello></div>`,
    components: {Hello},
    created : function(){
        console.log("root instance created")
    }
});

This doesn't work

I'd like to be able to use the same class syntax when creating the root vue instance:

app.vue

<template><hello></hello></template>

<script lang="ts">
    import Vue from 'vue'
    import Component from 'vue-class-component'
    import Hello from "./components/hello.vue"

    @Component({
        el: "#app",
        components: {Hello}
    })

    export default class App extends Vue {
        created() {
            console.log("created the root instance")
        }
    }
</script>

And then import app.vue in index.ts.

import Vue from "vue"
import App from "./components/app.vue"

let vm = new Vue(App)

Trying to use App to initialise the vue root instance gives this error:

Argument of type 'typeof Vue' is not assignable to parameter 
of type 'ComponentOptions<Vue> | undefined'

How can I define a ComponentOptions? And would it be possible that the entry point of the app is a .vue file instead of index.ts?

1

1 Answers

3
votes

The components section of an options object can specify components by spec or (apparently, I can't find this in the documentation) by including the component itself.

The Vue constructor does not accept a component, it requires a spec. Since a component is already an extension of Vue, so there's no reason to try to run it back through the Vue constructor. Just say

let vm = new App();

From the comments, it also turns out that specifying el should be left to the constructor call and not be included in the @Component, so it should be

let vm = new App({el: '#app'});