首页 > 解决方案 > Vue 使用来自 Vue() 的模板和脚本定义组件

问题描述

我正在尝试在我的全局 Vue() init 中定义一个组件,并已成功定义了该组件的模板,但似乎无法定义为模板执行工作的实际类。我正在使用带有打字稿的 Vue。

import ListClubsComponent from "./components/ts/list-club";

new Vue({
    el: "#app",
    components: {
        "list-clubs": {
            template: require("./components/clubs/list-clubs.html"),
            model: ListClubsComponent // This should be the class for the template
        }
    }
});

标签: javascripttypescriptvue.jsvuejs2vue-component

解决方案


不要在全局 Vue() 组件级别为您的组件定义模板,而是尝试在 './components/ts/list-club' 中定义它:

var ListClubsComponent = {
    template : ...,
    data:...
    ...
}

然后在全局 Vue() 组件中导入并注册整个组件:

import ListClubsComponent from "./components/ts/list-club";
new Vue({
    ...
    components : {
        'list-clubs' : ListClubsComponent
    }
    ...
})

这也应该更容易维护,因为模板与其功能组合在一起。

更多信息在https://vuejs.org/v2/guide/components-registration.html#Local-Registration


推荐阅读