vue實現提示儲存後退出的方法,vue實現儲存退出
假設有這樣一個需求,使用者在一個頁面內編輯文字,但是並未點擊儲存並且跳轉到了下一個路由。比較好的做法應該是給出一個提示—“您編輯的內容還未儲存,是否確認退出?”使用者如果點擊“確定”,那麼不儲存當前內容直接退出,使用者如果點擊“取消”,則取消本次路由跳轉,繼續留在原來的頁面。
嘗試的錯誤做法
一開始的時候我是想著使用vuex結合vue router的beforeEach導航守衛來實現。代碼如下:
首先在vuex中新增一個狀態值—introduceState
const store = new Vuex.Store({ strict: true, // process.env.NODE_ENV !== 'production', 直接修改state 拋出異常 state: { .... introduceState: false, .... }, getters: { introduceState: state => state.currentMenus }, mutations: { // 更新introduceState的值 changeIntroduceState (state, value) { state.introduceState = value } }})
使用者在點擊跳轉到另一個頁面的時候會觸發生命週期函數beforeDestroy,在這個函數中我們可以檢測使用者的編輯內容是否儲存,如果尚未儲存。
如果內容尚未儲存,我們就彈出一個提示框,當使用者選擇取消的時候,就將vuex中的introduceState值更新為true。
</script>import { mapGetters, mapActions, mapMutations } from "vuex"export default { data() { return { contentHasSave: false // 記錄使用者是否已經儲存內容 } }, methods: { ...mapMutations({ changeIntroduceState: changeIntroduceState }) }, beforeDestory: function(){ if(!contentHasSave){ // 使用element的提示框 this.$confirm('您還未儲存簡介,確定需要提出嗎?', '提示', { confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 選擇確定,正常跳轉 }) .catch(() => { // 選擇取消 this.changeIntroduceState(true) }) } }}</script>
最後在router的beforeEach的導航守衛裡監測from為當前頁面的所有路由跳轉。當state的introduceState為true的時候使用next(false)來取消本次路由跳轉
import Vue from "vue";import VueRouter from "vue-router";import routeConfig from "./routes";import {sync} from "vuex-router-sync";import store from "../store";//載入路由中介軟體Vue.use(VueRouter)//定義路由const router = new VueRouter({ routes: routeConfig, //mode: 'history'})sync(store, router)router.beforeEach((to, from, next) => { // 簡介也未提交,取消跳轉 if(from.fullPath === '/adwords/introduce' && store.state.introduceState === 'not-save'){ next(false) }})export default router
這種做法其實是行不通的,因為beforeEach方法的執行其實是在組件beforeDestory的方法之前執行的,也就是說beforeEach執行的時候introduceState的值根本沒有被更新為true。
正確的做法
後來自己去翻vue router的官方文檔,找到了一個絕妙的方法,那就是組件內的導航守衛。
const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染該組件的對應路由被 confirm 前調用 // 不!能!擷取組件執行個體 `this` // 因為當守衛執行前,組件執行個體還沒被建立 }, beforeRouteUpdate (to, from, next) { // 在當前路由改變,但是該組件被複用時調用 // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候, // 由於會渲染同樣的 Foo 組件,因此組件執行個體會被複用。而這個鉤子就會在這個情況下被調用。 // 可以訪問組件執行個體 `this` }, beforeRouteLeave (to, from, next) { // 導航離開該組件的對應路由時調用 // 可以訪問組件執行個體 `this` }}
上面的描述很清楚,於是我就在組件的js代碼裡加了一個beforeRouteLeave方法,然後彈出提示框,實現提示儲存後退出的功能。
</script>export default { data() { return { contentHasSave: false // 記錄使用者是否已經儲存內容 } }, // 組件內導航鉤子,處理未儲存退出的情況 beforeRouteLeave: function(to, from , next){ if(this.buttonText === '提交'){ next(false) this.$confirm('您還未儲存簡介,確定需要提出嗎?', '提示', { confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 選擇確定 next() }) } }}</script>
實現效果如下:
以上這篇vue實現提示儲存後退出的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。