首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在html中定义vue-router组件?

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

Stack Overflow用户
提问于 2019-02-18 12:01:22
回答 1查看 282关注 0票数 0

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

代码语言:javascript
复制
<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部分之外定义模板,如下所示:

代码语言:javascript
复制
<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路由器组件呢?我是vue新手..

EN

回答 1

Stack Overflow用户

发布于 2019-02-18 14:16:19

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

代码语言:javascript
复制
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')
代码语言:javascript
复制
<div id="app">
  <router-view/>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54740309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档