vue关于导航守卫的几种应用场景

beforeEach

该钩子函数主要用来做权限的管理认证

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

beforeRouteUpdate

路由参数改变时触发这个钩子,例如从/foo/1/foo/2 之间跳转的时候需要重新请求数据,这种类型的跳转不会触发created生命周期函数,可以通过该钩子函数或者监听$route来实现

<template>
  <div>
    {{ count }}
    <button @click="goRoute">跳转路由</button>
  </div>
</template>
<script>
export default {
  name: "foo",
  data() {
    return {
      count: 0,
    };
  },
  created() {
    console.log("id改变了");
    this.getData();
    
  },
  beforeRouteUpdate(to, from, next) {
    this.getData();
    next();
  },
  methods: {
    goRoute() {
      this.$router.push({
        name: "foo",
        params: {
          id: Math.floor(Math.random() * 10),
        },
      });
    },
    getData() {
      setTimeout(() => {
        this.count = this.$route.params.id * 2;
      }, 500);
    },
  },
};
</script>

beforeRouteLeave

用户未保存当前的内容就准备跳转,离开当前路由,可以通过该钩子弹出一个提示窗口

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章