如何在html中定义vue-router组件?

问题描述 投票:0回答:1

我正在使用django + vue.js + vue-router.js来制作我的项目。我正在尝试在单个html页面中使用vue-router。我搜索了一段时间,所有的例子都是使用.vue组件,或者简单地在js中定义组件模板,就像这样:

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

我想要的是在js部分之外定义模板,如下所示:

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

我试过这个,但不行。那么如何在html中定义vue-router组件呢?我很新vue ..

django vue.js vue-router
1个回答
0
投票

你需要在html文件中添加<router-view/>。例如

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>
© www.soinside.com 2019 - 2024. All rights reserved.