【问题标题】:Can I initialise the vue root instance with a .vue class component?我可以使用 .vue 类组件初始化 vue 根实例吗?
【发布时间】:2018-03-12 07:26:32
【问题描述】:

我正在使用vue-class-component,以便我可以在.vue 文件中使用类语法和打字稿类型检查。我可以使用这种语法创建 .vue 文件并将它们注册为组件,但根 Vue() 实例除外。

这行得通

hello.vue 文件看起来像这样,它使用 vue-class-component(为简洁起见)

<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>

现在,我可以像这样在根 vue 实例中导入 hello:

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")
    }
});

这不起作用

我希望在创建根 vue 实例时能够使用相同的类语法:

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>

然后在 index.ts 中导入 app.vue。

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

let vm = new Vue(App)

尝试使用App 初始化 vue 根实例会出现此错误:

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

如何定义 ComponentOptions?应用程序的入口点是否可能是 .vue 文件而不是 index.ts?

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    选项对象的components 部分可以通过规范指定组件,或者(显然,我在文档中找不到)通过包含组件本身来指定组件。

    Vue 构造函数不接受组件,它​​需要规范。由于组件已经是Vue 的扩展,因此没有理由尝试通过Vue 构造函数将其运行回来。直接说

    let vm = new App();
    

    从 cmets 还发现,指定 el 应该留给构造函数调用,而不是包含在 @Component 中,所以应该是

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

    【讨论】:

    • 也许我的措辞不清楚,但上面的代码适用于组件(它使用vue-class-component 来启用类语法)。我的问题是这种语法不适用于根 Vue 实例。
    • 您能否编辑您的问题以准确显示哪些有效,哪些无效?
    • 更新答案。
    • 这似乎有道理,但我明白了:option "el" can only be used during instance creation with the new keyword
    • 我不清楚@Component 是如何计算的。我自己没有使用过vue-class-component。可能如果您将 el 规范从 @Component 中删除并将其传递给构造函数:new App({el : '#app'})
    猜你喜欢
    • 2020-09-17
    • 2020-04-03
    • 2021-03-25
    • 2020-03-28
    • 2017-08-13
    • 2018-05-09
    • 2019-04-16
    • 2021-10-23
    • 2020-11-29
    相关资源
    最近更新 更多