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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM