1
votes

I'm trying to use vue-router to show different components for different route. However it doesn't seem to be working.

I have a codepen of the compiled program here.

My main.js is just defining the router and starting the vue application. It's importing the components and setting the routes.

import scss from './stylesheets/app.styl';

import Vue from 'vue';
import VueRouter from 'vue-router';
import Resource from 'vue-resource';

import App from './components/app.vue';
import Home from './components/home.vue';
import Key from './components/key.vue';
import Show from './components/show.vue';

// Install plugins
Vue.use(VueRouter);
Vue.use(Resource);

// Set up a new router
var router = new VueRouter({
  mode: 'history',
  routes:[
    { path: '/home', name: 'Home', component: Home },
    { path: '/key',  name: 'Key',  component: Key  },
    { path: '/show', name: 'Show', component: Show },

     // catch all redirect
    { path: '*', redirect: '/home' }
  ]
});

// For every new route scroll to the top of the page
router.beforeEach(function () {
  window.scrollTo(0, 0);
});

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

My app.vue is really very simple, just a wrapper div and the router-view

<script>
  export default {
    name: "app"
  }
</script>

<template lang="pug">
  .app-container
    router-view
</template>

The three other components that router should be showing are equally as simple, each looks basically the same. Just the name and the h1 content are different.

<script>
  export default {
    name: "home"
  }
</script>

<template lang="pug">
  h1 Home
</template>

Webpack build everything into an app.js without any errors. I have a super simple index.html file that I open in Chrome.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Sagely Sign</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="js/app.js"></script>
  </body>
</html>

Looking at the console I see no errors. What I do notice is the URL stays the same, it looks like the router is not redirecting to /home.

file:///Users/username/Development/test-app/build/index.html

I would have expected it to change to the new route.

file:///Users/username/Development/test-app/build/index.html#/!/home

But even if I goto that route directly the home.vue component is not displayed.

1

1 Answers

5
votes

The function you are using in the beforeEach method is a navigation guard. Navigation guards receive 3 parameters: to, from and next. From the Navigation Guards documentation:

Make sure to always call the next function, otherwise the hook will never be resolved.

Here, you just scroll at the top of the page but the hook is never resolved, therefore the router stops here, right after the scroll.

Write your function like this:

router.beforeEach(function (to, from, next) {
    window.scrollTo(0, 0);
    next();
});

And it should work.