0
votes

I'm using django + vue.js + vue-router.js to make my project. I'm trying to use vue-router in a single html page. I searched for a while, all examples are use .vue components, or define the component templates in js part simpely, just like this:

<body>
    <div id="app">
        <div>
            <router-link to="/foo">Go to Foo</router-link>
            <router-link to="/bar">Go to Bar</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>
    <script>
        const Foo = { template: '<div>foo</div>' }
        const Bar = { template: '<div>bar</div>' }

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

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

What I want is define the template outside the js part something like this:

<body>
    <div id="app">
        <div>
            <router-link to="/foo">Go to Foo</router-link>
            <router-link to="/bar">Go to Bar</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>

    <template id="Foo">
        <div>this is Foo</div>
    </template>
    <template id="Bar">
        <div>this is Bar</div>
    </template>

    <script>
        const Foo = { template: '#Foo' }
        const Bar = { template: '#Bar' }

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

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

I tried this, but not work. So how to define vue-router components inside a html? I'm new with vue..

1
Where is <div id="app"> in your HTML? - Sajib Khan
Why dont you want to use .vue files to hold your components and their templates? Putting all of the templates in the same html completely defeats the purpose of components, and you wind up with one gigantic file housing your entire web app. - jpriebe

1 Answers

0
votes

You need to add <router-view/> in html file. e.g.

const Foo = { template: '<div>this is Foo</div>' }
const Bar = { template: '<div>this is Bar</div>' }

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

    const router = new VueRouter({
        routes
    })

    const app = new Vue({
        router
    }).$mount('#app')
<div id="app">
  <router-view/>
</div>