router-link and href not working in Vue js

Kushagra Agarwal picture Kushagra Agarwal · Jul 29, 2017 · Viewed 19.2k times · Source

I am learning vue js and i created an admin page which i am able to route when i am using router-view but when i am trying href or router-link i am not able to load the template thought the url gets changed.

this is my main.js

    import Vue from 'vue'
    import VueResource from 'vue-resource'
    import VueRouter from 'vue-router'
    import App from './App.vue'

    import admin from "./components/admin/admin.vue"
    import users from "./components/users.vue"


    Vue.use(VueRouter);
    Vue.use(VueResource);

    const router = new VueRouter({
        routes: [
            {path:'/admin',component:admin},
            {path:'/users',component:users},

        ]
    })


    new Vue({
        el: '#app',
        router: router,

        render: h => h(App)
    })

this is my app.vue

this is my app vue file which just want to route to a page via href

    <template>
      <div class = "container" id="app">

          <h1>Hi from</h1>

          <hr>
          <a href="/api/users">sdsd</a>


      </div>
    </template>

    <script>


    export default {
      name: 'app',

      data(){
        return{
          users: ""
        }
      }
    }
    </script>

    <style>
    #app {

    }
    </style>

this is my admin.vue

this the template i want to load in my app.vue its a simple template i want to display in app.vue. its somehow working router-view but it is not working with router-link

<template>
    <div class="container">
        <h1>
            HI i am routing from admin
        </h1>
    </div>
</template>

the above thing is working via router-view but not thing router-link or href anchor tags............................................................................................................................................................................................

Answer

Vamsi Krishna picture Vamsi Krishna · Jul 29, 2017

1.You are building a SPA using vue and vue-router. The routing is handled by javascript only. So you do not need to pass URLs to href in <a> tags .

2.You should use <router-link> for navigation which will eventually be rendered as <a> tag.

3.You use to attribute of <router-link> as a prop to pass the link you want to navigate to.

4.You require <router-view></router-view> to display or render the component matched by the roite.

So your App.vue should be:

<template>
  <div class = "container" id="app">

      <h1>Hi from App.vue</h1>

      <hr>
      <router-link to="/users">Users</router-link>
      <router-link to="/admi">Admin</router-link>

    router-view></router-view>
  </div>
</template>

<script>


export default {
  name: 'app',

  data(){
    return{
      users: ""
    }
  }
}
</script>

<style>
#app {

}
</style>