我正在尝试使用 vue-router 和 router-link
。当我单击链接时,URL 会正确更新,但没有任何内容加载到 <router-view></router-view>
中。我猜这与使用 unpkg CDN 而不是使用 vue-CLI 构建它有关?我不太确定为什么这不起作用。
索引.html
....
<body>
....
<nav id="app">
<li><router-link to="/hello">Hello</router-link></li>
<nav>
<!--view-->
<router-view></router-view>
....
<!--vue.js-->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<!--router-->
<script src="js/router.js"></script>
</body>
路由器.js
const Hello = { template: '<div>test</div>' }
const routes = [
{ path: '/hello', component: Hello }
]
const router = new VueRouter({
routes
})
const app = new Vue({
router
}).$mount('#app')
我试过删除 <li> </li>
周围的 router-link
,但这似乎没有帮助。
原文由 rpivovar 发布,翻译遵循 CC BY-SA 4.0 许可协议
您正在使用
const app = new Vue({})
,这将创建一个新的 vue 实例那么您正在使用
$mount()
将元素选择器作为参数。$mount()
所做的是,它手动将 Vue 实例安装到您作为参数传递的关联 DOM 元素In your code, only the
nav
element has the id ofapp
which means only thenav
element is mounted to your Vue instance not therouter-view
在nav
元素之外。这就是为什么您添加 ID 为
app
的包装器的答案有效,因为现在router-view
也与 Vue 实例相关联。您可以参考:
vm.$mount() , Vue 实例