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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM