• 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)
      }
    }
    
  • 相关阅读:
    C++--第25课
    C++--第24课
    C++--第23课
    C++--第22课
    C++--第21课
    C++--第20课
    C++--第19课
    C++--第18课
    C++--第17课
    Windows程序设计学习笔记(1):一个简单的windows程序
  • 原文地址:https://www.cnblogs.com/genhao7/p/14283463.html
Copyright © 2020-2023  润新知