【问题标题】:How to import Vue.js component from external file如何从外部文件导入 Vue.js 组件
【发布时间】:2018-06-17 18:06:34
【问题描述】:

我在 HTML 脚本标签中有路由块

const routes = [
        {path: '/foo', component: Foo},
        {path: '/bar', component: Bar}
    ];

如何导入存储为单独文件的 Foo.vue 文件的内容?

Foo.vue

<template>
    <div>
        foo
    </div>
</template>

我尝试了不同的方法,例如 script id="foo" src="js/foo.vue" 或直接在块中导入,但都没有奏效。

Vue.js 有没有办法导入外部 vue 文件的内容?

索引.html:

<script id="foo" src="js/foo.vue"></script>
<script>
    Vue.use(VueMaterial.default);

//    const Foo = {template: '<div>foo</div>'};
    const Bar = {template: '<div>bar</div>'};

    const routes = [
        {path: '/foo', component: Vue.component('foo')},
        {path: '/bar', component: Bar}
    ];

    const router = new VueRouter({
        routes
    });

    new Vue({
        name: "Normal",
        router
    }).$mount("#app");
</script>

【问题讨论】:

  • .vue 文件(或单个文件组件)需要编译成纯 JavaScript 才能在浏览器中工作。为此你需要一个构建系统(通常是 webpack),检查:For Users New to Module Build Systems | Single File Components — Vue.js
  • 感谢您的回答。不幸的是,我不知道如何使用 webpack 或其他 JS 构建工具——我不是一个真正的 JS 人。我只想分隔文件。好的,我可以在路由定义中使用html文件而不是vue文件吗?就像 Angular 中的 templateUrl 一样。
  • 有一个 vue-cli 包可以帮助您使用 webpack(或 browserify)设置一些项目模板,您可能值得一看
  • 谢谢,我会试试这些模板。

标签: javascript vuejs2


【解决方案1】:

如果您查看下面的示例,我的组件有单独的文件;一个使用 vue-class-component/vue-property-decorator 的 typescript 文件,一个 html 文件和一个 less 文件。然后我将所有这些添加到 .vue 文件中的相关标签中。我发现我必须从我正在导入的文件中导入和导出我的类。

<template src="./example.html"></template>
<script lang="ts">
import ExampleClass from './example-class';
export default ExampleClass;
</script>
<style lang="less" src="./example.less"></style>

通过将它们全部保存在单独的文件中,如果 vue 文件中有另一个 vue 组件,则可以只导入类内容而不是完整的 .vue 文件。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多