'vue-router : router-link not working
I'm trying to use vue-router and router-link
. When I click on the link, the URL updates correctly, but nothing is loaded into <router-view></router-view>
. I'm guessing this has something to do with using the unpkg CDNs rather than building this with vue-CLI? I'm not really sure why this isn't working.
index.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>
router.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')
I've tried removing the <li> </li>
around the router-link
, but this doesn't seem to help.
Solution 1:[1]
You are using const app = new Vue({})
, this creates a new vue instance
then you are using $mount()
which takes in an element selector as an argument.
What $mount()
does is, it manually mounts the Vue instance to the associated DOM element that you pass as the argument
In your code, only the nav
element has the id of app
which means only the nav
element is mounted to your Vue instance not the router-view
which is outside of the nav
element.
That is why your answer of adding a wrapper with an id of app
works because now the router-view
is also associated with the Vue instance.
You can refer to:
Solution 2:[2]
It works when I attach the app
id to a wrapper <div>
around everything, like this:
....
<div id="app">
<nav>
<li><router-link to="/hello">Hello</router-link></li>
<nav>
</div>
Solution 3:[3]
In my case router-link is not working because i have sidebar outside of <div id="app"></div>
So the moral of the story is we have to put all vue related element or stuff in the div which we have used for mounting in app.js
So Structure of html Should be as Below:
<html>
<body>
<div id="app">
<aside>
<!-- sidebar -->
<li><router-link to="/users">Users</router-link></li>
<li><router-link to="/home">Home</router-link></li>
</aside>
<div class="content">
<!-- Main content -->
<event-hub></event-hub>
<router-view></router-view>
</div>
</div>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joshua Trimm |
Solution 2 | rpivovar |
Solution 3 | Haritsinh Gohil |