我正在使用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的新手。.
答案 0 :(得分: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>