vue.js之路由Router(三)路由守卫的应用

路由守卫的应用

组件导航的巧用

  • 除了应用于导航栏外,组件导航还可应用用去往详情页:
<template>
  <el-row class="menu-card" type="flex" justify="start">
    <el-col
      v-for="item in info"
      :key="item._id"
      style="flex: none"
      :style="{ 'margin-left': marginLeft + 'px' }"
    >
      <el-card :body-style="{ padding: '0px' }">
        <router-link :to="{ name: 'detail', query: { menuId: item._id } }">
          <img
            :src="item.product_pic_url"
            class="image"
            style="width: 232px; height: 232px"
          />
          <div style="padding: 14px" class="menu-card-detail">
            <strong>{{ item.title }}</strong>
            <span>{{ item.comments_len }} 评论</span>
            <router-link
              :to="{ name: 'space', query: { userId: item.userId } }"
              tag="em"
            >
              {{ item.name }}
            </router-link>
          </div>
        </router-link>
      </el-card>
    </el-col>
  </el-row>
</template>

由于a标签内不能再写a标签,因此router-link里边的router-link加上tag=“em”,意为渲染成em标签

组件内的守卫的应用

  • 比如在别的页面在离开当前页面之前,需要一些操作
beforeRouteLeave(to, from, next) {
    if(to.name === "business_create") {
        ......
    }
    } else{
        next();
    },
  • beforeRouteUpdatebeforeRouteEnter用法相同

全局守卫的应用

  • 最常见的应用于页面鉴权登录
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem("token");
  const isLogin = !!token;

  // 进入路由的时候,都要想后端发送token,验证合法不合法
  // 不管路由需要不需要登录,都需要展示用户信息
  // 都需要向后端发请求,拿到用户信息
  const data = await userInfo();
  Store.commit("chnageUserInfo", data.data);
  // 判断哪些页面需要登录
  if (to.matched.some((item) => item.meta.login)) {  
    // 需要登录,判断登录状态
    if (isLogin) {
      if (data.error === 400) {
        // 后端告诉你,登录没成功
        next({ name: "login" });
        localStorage.removeItem("token");
        return;
      }
      if (to.name === "login") {
        next({ name: "home" });
      } else {
        next();
      }
      return;
    }
    // 没登录,进入login,直接进入
    if (!isLogin && to.name === "login") {
      next();
    }
    // 没登录,进入的不是login,跳到login
    if (!isLogin && to.name !== "login") {
      next({ name: "login" });
    }
  } else {
    next();
  }
});

路由独享守卫的应用

const router = new VueRouter({
  routes: [
    {
      path: "/foo",
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      },
    },
  ],
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值