【问题标题】:Ho to define vue-router components inside a html?如何在 html 中定义 vue-router 组件?
【发布时间】:2019-07-11 10:13:04
【问题描述】:

我正在使用 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 新手..

【问题讨论】:

  • &lt;div id="app"&gt; 在您的 HTML 中的什么位置?
  • 您为什么不想使用.vue 文件来保存您的组件及其模板?将所有模板放在同一个 html 中完全违背了组件的目的,您最终会得到一个包含整个 Web 应用程序的巨大文件。

标签: django vue.js vue-router


【解决方案1】:

您需要在 html 文件中添加&lt;router-view/&gt;。例如

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>

【讨论】:

  • 是的。我已经添加了&lt;router-view/&gt;。代码未粘贴在这里(我会更新)。我的问题是如何将模板定义移出 js 部分,而不是作为 js 字符串。
  • &lt;div id="app"&gt; 在您的 HTML 中的什么位置?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2019-11-14
  • 2020-02-15
  • 2016-11-09
  • 2017-09-05
  • 2018-04-22
相关资源
最近更新 更多