vue.js – $router.push is not working in VueJS

Question:

Good night, I'm starting my studies in web development and I chose VueJS with Vuetify to start. Right away I'm not able to change the page when clicking a button. I installed vue-router through NPM and created the router.js file with the following code:

import Vue from 'vue'
import Router from 'vue-router'
import App from './App.vue'
import Dashboard from  './Dashboard.vue'

Vue.use(Router)

export default new Router({
mode: 'history',
routes: [
  {
    path: '/',
    name: 'App',
    component: App
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard
  }
]
})

Then I imported this file into main.js:

new Vue({router,vuetify,render: h => h(App)}).$mount('#app')

On the button I put the following code:

@click="$router.push('/dashboard')"

Clicking the button changes the URL address correctly, but the page does not switch to the Dashboard component. On the console, no error is shown. I searched but couldn't find the problem. Can anybody help me?

Answer:

To navigate between pages you have several options:

1) Using router-link :

// Hardcoded Link
<router-link to="/dashboard">Go to Dashboard</router-link>

// Usando nome da rota
<router-link :to="{name: 'Dashboard'}">Go to Dashboard</router-link>

2) Programmatic navigation:

// literal string path
this.$router.push('dashboard')

// object
this.$router.push({ path: 'Dashboard' })

Finally don't forget to use router-view in the input component, in this case probably in App.vue

// App.vue

<div>
 <router-view></router-view>
</div>
Scroll to Top