0

Route change doesn't scroll to top, so Vue creator advises to use navigation guards. In the updated version:

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

Perfect, except it yields this fatal error in my app: ncaught TypeError: vue_router__WEBPACK_IMPORTED_MODULE_1__.default.beforeEach is not a function

Why?

Just in case here's my complete router.js file:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import PastEvents from './views/PastEvents.vue'
import BasicPage from './views/BasicPage.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/past-events',
      name: 'past-events',
      component: PastEvents
    },
    {
      path: '/basic-page',
      name: 'basic-page',
      component: BasicPage
    }
  ]
})

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

1 Answer 1

9

You've capitalized Router, that's the class name. What you want to do is add your .beforeEach() to the instance of the router. You'll notice in the documentation that it's always a lowercase router they're adding the guards to.

Currently, you're immediately exporting the instance from the module, so you'll need to first add it to a variable when you create a new Router and then add your .beforeEach() clauses to it before finally exporting it.

const router = new Router({
  ...
})

router.beforeEach( ... )

export default router
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.