zoukankan      html  css  js  c++  java
  • 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)
      }
    }
    
  • 相关阅读:
    如果你很忙,你一定在什么地方做错了!
    NOSQL介绍
    mysql 8.0.11 安装(windows)
    ORA-28547:(Navicat Premium连接oracle报错)
    线性筛法
    Luogu-P1020(导弹拦截)(DP,LIS ,二分优化)
    POJ
    HDU
    HDU-1024-Max Sum Plus Plus(DP)
    UVA-1625-Color Length(DP LCS变形)
  • 原文地址:https://www.cnblogs.com/genhao7/p/14283463.html
Copyright © 2011-2022 走看看