vue 路由配置 路由守卫(beforeEach、router.afterEach,beforeEnter)WEBPACK_IMPORTED_MODULE_1__.default.beforeEac

首先最简单的就是在创建框架的时候选择router 在里边进行路由的添加

没有的话  那就需要从新安装路由

下载安装vue-router

npm install --save vue-router@3

 main.js  按需求引入  

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'


import echarts from 'echarts'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false

Vue.use(ElementUI)

import dataV from '@jiaminghi/data-view'

Vue.use(dataV)
var axios = require('axios')
axios.default.baseURL = '/api'
 
Vue.prototype.$http = axios //正确的使用 



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

嵌套路由  注意名字的大小写   

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

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    },
    {
      path: '/demo',
      name: 'Demo',
      component: () => import(/* webpackChunkName: "about" */'./views/Demo.vue')
    },
    {
      path: '/helloworld',
      name: 'HelloWorld',
      component: () => import(/* webpackChunkName: "about" */'./components/HelloWorld.vue')
      // 子级路由  
      // children: [
      //   {
      //     path: '/demo',
      //       name: 'Demo',
      //       component: () => import(/* webpackChunkName: "about" */'./views/Demo.vue')
      //   }
      // ]
    }
  ]
})

使用 

--------------------------------------------------------------------------------------------------------------------------------

前置路由写法

全局前置守卫
router.beforeEach(function (to, from, next) {
    //第一个参数to,包含的内容是切换后的路由对象,也就是跳转后的路由对象
    //第二个参数from,包含的内容的是切换前的路由对象,也就是跳转前的路由对象
    //第三个参数next(),是否往下执行,执行的话,如果不写的话路由就不会跳转,操作将会终止
    //to 要去的路由地址  from 从那个地址过来的  next() 可以跳转  next('url') 跳转到指定地址
    console.log(from);
    next(); //完成跳转
})


前置路由有数据演示


// 注册全局前置导航守卫
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if (to.path === '/login') {//若跳转的路径为登陆页面
    next();
  } else {//请求的是其他路径:判断是否已经登陆过
    if (sessionStorage.getItem('isAuth') === 'true') {
      next();
    } else {//用户未登录
      next({//强制跳转到登录页面
        path: '/login',
        query: {//查询,重定向至login的完整路径
          redirect: to.fullPath
        }
      })
    }
  }
})

 后置路由

 
全局后置路由守卫
router.afterEach(function (to, from) {
    //第一个参数to,包含的内容是切换后的路由对象,也就是跳转后的路由对象
    //第二个参数from,包含的内容的是切换前的路由对象,也就是跳转前的路由对象
    console.log(from, to);
})

独享路由

 
独享守卫
beforeEnter: (to, from, next) => {
    //第一个参数to,包含的内容是切换后的路由对象,也就是跳转后的路由对象
    //第二个参数from,包含的内容的是切换前的路由对象,也就是跳转前的路由对象
    //第三个参数next(),是否往下执行,执行的话,如果不写的话路由就不会跳转,操作将会终止
    console.log(to);
    next();
}

组件路由

export default {
  beforeCreate() {
    console.log("创建之前");
  },
  //组件内守卫-进入之前
  beforeRouteEnter(to, from, next) {
    console.log("路由进入之前");
    next();
  },
  //组件内守卫-离开之前
  beforeRouteLeave(to, from, next) {
    console.log("路由离开之前");
    next();
  },
  beforeDestroy() {
    console.log("销毁");
  },
  //组件内守卫-路由更新 (子路由或路由参数的变化)
  beforeRouteUpdate() {},
};

全部  参考 别的博主 

// 该文件专门用于创建整个应用的路由器
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
// 1.下载vue-router: npm i -S vue-router@3
// 2.使用插件vue-router
Vue.use(VueRouter)

// 3.配置路由规则
const routes = [
  {
    path: '/',
    // 路由重定向 默认显示当前路由页面
    redirect: '/about',
    // 后置路由守卫,需要每个都配置  meta
    meta: { title: '首页' }
  },
  {
    name: 'shouye',
    // 路径
    path: '/home',
    // 组件
    component: Home,
    redirect: '/home/news',
    meta: { title: '首页' },
    children: [
      // 二级路由不要加 /
      {
        name: 'xinwen',
        path: 'news',
        component: () => import('../views/News.vue'),
        meta: { title: '新闻' }
      },
      {
        name: 'xinxi',
        path: 'message',
        component: () => import('../views/Message.vue'),
        // 前置路由守卫 用于标识是否需要权限验证  meta 配置项 不能变  isAuth 可以自己设置  isAuth: true 没有权限访问
        meta: { isAuth: true, title: '信息' },
        // 三级嵌套路由
        children: [
          {
            name: 'xiangqing', // 给路由取别名,最好是唯一的
            // query
            // path:'detail',
            // params
            path: 'detail/:id/:title', // /: 使用占位符声明接收params参数
            component: () => import('../views/Detail.vue'),
            meta: { title: '详情' }

            // props配置
            // 第一种写法:props值为对象  该对象中所有的key-value的组合最终都会通过props传给Detail组件
            // props:{id:111,title:'lala'}

            // 第二种写法:props值为布尔值,布尔值为true  则把路由收到的所有params参数通过props传给Detail组件
            // props:true,  // 仅用于params参数

            // 第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
            /*  props(route) {
              // 适用于query参数和params参数
              return {
                id: router.params.id,
                title: TouchEvent.params.title
              }
            } */
            // 利用结构赋值,简化第三种方法
            /*  props({params:{id,title}}){
              return{
                id,
                title
              }
            } */
          }
        ]
      }
    ]
  },
  {
    path: '/about',
    component: () => import('../views/About.vue')
  }
]

// 4.创建并暴露 路由器
const router = new VueRouter({
  routes,
  // mode:'hash'  // 有#
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  // 2.若数据太多,可以用数组验证
  // const arr=['xinwen','xinxi','xuesheng','zuoye']
  // if(arr.indexOf(to.name))
  // 3.通过  meta 标识
  if (to.meta.isAuth) {
    // 1.可以用name进行验证
    // if (to.name === 'xinwen' || to.name === 'xinxi') {
    // 需要进行权限验证
    // console.log('需要进行权限验证')
    if (localStorage.getItem('username') === 'admin') {
      next()
    } else {
      alert('您没有权限请登录')
    }
  } else {
    // 无需权限验证  如:登录页面,注册页面  404页面
    next()
  }
})

// 后置路由守卫  to,from
router.afterEach((to) => {
  document.title = to.meta.title || '北京昌平'
})

export default router

 报错

router.js:142 Uncaught TypeError: vue_router__WEBPACK_IMPORTED_MODULE_1__.default.beforeEach is not a function

主要原因写法不对 

 

写法

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

Vue.use(Router)
// 2.创建Router对象
const routes = [{
  path: '/',
  name: 'home',
  component: Home
},
{
  path: '/about',
  name: 'about',
  component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
},
{
  path: '/demo',
  name: 'Demo',
  component: () => import(/* webpackChunkName: "about" */'./views/Demo.vue'),
},
{
  path: '/Data',
  name: 'data',
  component: () => import(/* webpackChunkName: "about" */ './xiangmu1/Data.vue')
}
]

// router.beforeEach(function(to, from, next) {
// // 从from跳转到to
// console.log('asas')
// document.title = to.meta.title;
// next();

// })

// // 前置路由 登录前进行判断
// router.beforeEach(function (to, from, next) {
//   // 从from跳转到to
//   console.log('asas')
//   document.title = to.meta.title;
//   next();
// })

// 4.创建并暴露 路由器
const router = new Router({
  routes,
  mode: 'history',
  // // 定义路由的 模拟 是哈希  还是history
  // mode:'hash'  // 有#
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  console.log('测试')
  // 2.若数据太多,可以用数组验证
  // const arr=['xinwen','xinxi','xuesheng','zuoye']
  // if(arr.indexOf(to.name))
  // 3.通过  meta 标识

  // 这里的数据根据你的情况判断啊 
    let token = getToken()
  if (token) {
    // 有token访问login页面,就跳到首页
    if (to.path === '/login') {
      next('/login')
    } else {
      if (store.getters.realName === '') {
        store.dispatch('pullUserInfo').then(resp => {
          //获取用户信息失败  返回登录界面
          if (resp === null) {
            store.dispatch('logout').then(() => {
              next('/login')
            })
          }
          
          next({
            ...to,
            replace: true
          })
        }).catch(res => {
          //如果不是登陆过期或未登陆,退出登陆
          if (res.code !== '10204') {
            store.dispatch('logout').then(() => {
              next('/login')
            })
          }
        })
      } else {
        next()
      }
    }
  } else {
    // 白名单,免密登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 否则就跳动登录页面
      next('/login')
    }
  }

})

// 后置路由守卫  to,from
router.afterEach((to) => {
  document.title = to.meta.title || '北京昌平'
})

export default router

参考

vue路由全局前置守卫_router-guards_zj_zjk_sjz的博客-CSDN博客

__WEBPACK_IMPORTED_MODULE_1_vue_router__.a.beforeEach is not a function_芜独独的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值