vue2.0组件内的守卫(beforeRouteLeave实现 编辑未保存,弹窗提示)

html

 <el-form-item label="姓名:" prop="name">
   <el-input v-model="Form.name" placeholder="请输入姓名" @change="changeNoSave"></el-input>
 </el-form-item>
 <el-form-item>
   <el-button  @click="submitForm('Form')"> 保 存 </el-button
 </el-form-item> 
  beforeRouteLeave(to, from, next) {
    if (this.change_nosave) {
      this.$confirm("您填写的内容未保存,确定离开吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: false
      }).then(() => {
        next();
      });
    } else {
      next();
    }
  },
  data(){
    return{
        change_nosave :false
    }
  },
  methods: {
    changeNoSave(status) {
      this.change_nosave = status;
    },
  submitForm(formName) {
      this.change_nosave = false;
  }
  } 
1.beforeRouteEnter

  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
 注:beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

2.beforeRouteUpdate (2.2 新增)

  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  }
例:
beforeRouteUpdate (to, from, next) {
  // just use `this`
  this.name = to.params.name
  next()
}
  

}, 3.beforeRouteLeave

  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。
例:
beforeRouteLeave (to, from , next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}

 

转载自:https://juejin.im/post/5c14bea8e51d455e3e555579

posted @ 2020-06-05 10:56  优雅的小谢  阅读(2620)  评论(0编辑  收藏  举报
Live2D