3

Vue编程式路由导航和路由守卫

 2 years ago
source link: https://www.fly63.com/article/detial/11225
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
更新日期: 2022-02-25阅读量: 38标签: 路由分享

扫一扫分享

<router-link>的replace属性

作用:控制路由跳转时操作浏览器历史记录的模式

浏览器历史记录有两种写入方式:分别有push和replace,push是追加历史记录,replace是替换当前记录,路由跳转时是push

如何开启replace模式:

<router-link replace ...>news</router-link>

编程式路由导航

作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活

具体编码:

methods: {
  pushShow(m) {
    this.$router.push({
      name: 'msg-d',   // 就是路由的名称,不能使用path
      params: {
        id: m.id,
        title: m.title,
        views: m.views
      }
    })
  },
  replaceShow(m) {
    this.$router.replace({
      name: 'msg-d',   // 就是路由的名称,不能使用path
      params: {
        id: m.id,
        title: m.title,
        views: m.views
      }
    })
  },
  back() {  // 后退
    this.$router.back()
  },
  forward() {   // 前进
    this.$router.forward()
  },
},

全局路由守卫

// 全局前置路由守卫——初始化的时候被调用,每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if(to.meta.isAuth){
    if(localStorage.getItem("user") === 'xiansen'){
      next();
    }else{
      alert("您没有权限!");
    }
  }else{
    next();
  }
})

// 全局后置路由守卫——初始化的时候被调用,每次路由切换之后被调用
router.afterEach((to, from) => {
  // to and from are both route objects.
  document.title = to.meta.title || '测试vue脚手架'
})

独享路由守卫(在路由中配置该属性,方法功能和上面的一样)

beforeEnter:(to, from, next) => {   // 独享路由守卫
  if(to.meta.isAuth){
    if(localStorage.getItem("user") === 'xiansen'){
      next();
    }else{
      alert("您没有权限!");
    }
  }else{
    next();
  }
},

链接: https://www.fly63.com/article/detial/11225


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK