1
votes

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.

3
I was getting this issue due to some hacky code in the vue-material library. Not to be confused with vuetify. github.com/vuematerial/vue-material/issues/1977Ray Foss

3 Answers

7
votes

You are using const app = new Vue({}), this creates a new vue instance

then you are using $mount() which takes in a element selector as 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 nav element.

That is why your answer of addimg a wrapper with id of app works, because now the router-view is also associayed to the vue instance.

You can refer to:

vm.$mount() , Vue instance

1
votes

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>
1
votes

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>