路由守卫之组件内前置守卫的详细介绍

在这里插入图片描述

使用场景:

当我在项目中使用keep-alive缓存机制的时候,当我们新增一个列表数据时页面不刷新,但我们还想保留keep-alive缓存,这时候怎么办呢?就会用到路由守卫,进入组件的时候刷新页面

  • 首先我是从其他页面新增的数据,需要先存一个唯一标识:
 this.$posts(
     "/api/employee/entry",
     this.encode(finish)
   ).then((res) => {
     // console.log(res, "入职完成按钮成功了");
     if (res.success == true) {
       console.log(this.is_create);

       if (this.is_create == 0) {
          window.sessionStorage.setItem('flag',true)
          this.$router.push("/onjob");
        
       } else {
         this.$router.push("/waitjob");
 }
  • 然后在你想刷新的页面设置路由导航的前置守卫:
  1. 组件内的前置守卫beforeRouteEnter((to,from,next)=>{})
  2. 导航进入组件时,调用
  3. this是访问不到的,如果非要访问this ,必须通过next(vm=>{}) 访问
  4. 因为组件此时没有创建,所以没有this
  5. 案例: 数据预载(进入组件前就获得数据)
beforeRouteEnter(to, from, next) {
    next(vm => {
      //vm指的就是组件
      const getFlag = window.sessionStorage.getItem('flag');
      console.log(getFlag,'取');
      
      if (getFlag == 'true') {
        console.log(111);       
        vm.reset();
        window.sessionStorage.clear();
      }
    });
  },

这样就实现了页面的刷新功能,是不是很nice
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hong521520/article/details/107079549