drake035
drake035

Reputation: 2897

Vue: beforeEach is not a function

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();
})

Upvotes: 0

Views: 5390

Answers (1)

Soviut
Soviut

Reputation: 91595

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

Upvotes: 9

Related Questions