0
votes

I have routes block in HTML Script tag

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

How can I import content of Foo.vue file stored as a separate file?

Foo.vue

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

I have tried different ways like script id="foo" src="js/foo.vue" or direct import in block, but none of them worked.

Is there way with Vue.js to import content of external vue file?

Index.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>
1
.vue files (or Single File Components) need to be compiled into plain JavaScript in order to work in the browser. For that you need a build system (usually webpack), check: For Users New to Module Build Systems | Single File Components — Vue.jsyuriy636
Thanks for the answer. Unfortunately I don't know how to use webpack or other JS build tools - I'm not really a JS guy. I just want to separate files. Okay, can I use html files instead of vue files in routing definition? Just like with templateUrl in Angular.Evgeny Karpov
There is a vue-cli package that helps you setup some a project template with webpack (or browserify) it may be worthwhile for you to have a look into itDaniel
Thanks, I'll try these templates.Evgeny Karpov

1 Answers

1
votes

If you look at my example below, I have separate files for my component; a typescript file that uses vue-class-component/vue-property-decorator, a html file and a less file. I then add all of these into the relevant tags in a .vue file. I found that I had to import and export my class from the file i was importing in.

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

By keeping them all in separate files, if you have another vue component in a vue file, you can just import the class contents rather than the full .vue file.

hope this helps