3502
2021-03-18 17:58
采纳率: 50%
浏览 348

Vue报错beforeEach is not a function

import Vue from 'vue'
import Router from 'vue-router'
/* import User from '../components/User'
import Home from '../components/Home'
import About from '../components/About' */
import VueRouter from 'vue-router'


const Home =() => import ('../components/Home')
const About =() => import ('../components/About')
const User =() => import ('../components/User')
const HomeNew =() => import ('../components/HomeNews')
const Homemessage =() => import ('../components/Homemessage')

Vue.use(Router)

export default new Router({
 
  mode: 'history',
  linkActiveClass:'active',

  routes: [
    {
      path:'',
      //redirect重定向
      redirect:'/home'
    },
    {
      path: '/home',
      component: Home,
      
      meta:{
        title:'首页'
      },
      children:[
        {
          path:'',
          //redirect重定向
          redirect:'news'
        },
        {
          path:'news',
          component:HomeNew
        },{
          path:'message',
          component:Homemessage
        },
      ]
    },
    {
      path: '/about',
      component:About,
      meta:{
        title:'关于'
      },
    },
    
    {
      path:'/user/:userId',
      component:User,
      meta:{
        title:'用户'
      },
    }
  ]
 
})
Router.beforeEach((to,from,next) => {
  //从from跳转到to
  document.title = to.matched[0].meta.title
  console.log(to);
  next()
})

刚接触vue路由不明白是哪里出现问题,求大佬指点

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • 流转的年华 2021-03-19 10:01
    已采纳

    你这个router定义的时候是匿名的,所以使用的时候找不到,你可以这样改:

    const routes = [
     //界面路由
    ]
    const router = new VueRouter({
      mode:'history',
        linkActiveClass:'active',
    
       routes })
    
    router.beforeEach((to, from, next) => {
     //业务逻辑
    }
    export default router
    2 打赏 评论
  • whicce 2021-03-18 18:05

    第六行改成import Router from 'vue-router'试试

    打赏 评论
  • 因该用VueRouter.beforeEach(),应为你引入vue-router赋值给了VueRouter

    打赏 评论
  • z_mango 2021-03-18 21:17
    export default new Router({
    Router.beforeEach((to,from,next) => 

    这两行放一起,是不是能看明白?

    Router还没有实例化

     

    在main.js里 
     

    import Router from "./router/index.js"; //你的路由配制地址
    
    Router.beforeEach((to,from,next) => {
    
    //从from跳转到to
    document.title = to.matched[0].meta.title
    console.log(to);
    next()
    })

    全局守卫放MAIN.JS也没得问题

    打赏 评论
  • 流转的年华 2021-03-19 10:01

    你这个router定义的时候是匿名的,所以使用的时候找不到,你可以这样改:

    const routes = [
     //界面路由
    ]
    const router = new VueRouter({
      mode:'history',
        linkActiveClass:'active',
    
       routes })
    
    router.beforeEach((to, from, next) => {
     //业务逻辑
    }
    export default router
    打赏 评论

相关推荐 更多相似问题