单个路由的钩子
beforeEnter
进入某个个路由前执行。
应用场景
- 将上一个组件传过来的参数拼到新的路由的后边
// 写在路由文件的js的某个路由中 const routes = [ { path: '/', beforeEnter: (to, from, next) => { const href = window.location.href const queryString = href.slice(href.indexOf('?')) // 即将跳转到某个路由之前,把上一个路由的参数拼接在要重定向的路由的后面 // 可以用来初始化页面数据 next({ path: `/home/dashboard${queryString}`, replace: true }) } }, // ... ]
组件内的钩子
应用场景1:清除当前组件中的定时器
当一个组件中有一个定时器时, 在路由进行切换的时候, 可使用beforeRouteLeave将定时器进行清楚, 以免占用内存。
beforeRouteLeave (to, from, next) { window.clearInterval(this.timer) //清除定时器 next() }
应用场景2:页面中有未关闭的窗口, 或未保存的内容时, 阻止页面跳转
如果页面内有重要的信息需要用户保存后才能进行跳转, 或者有弹出框的情况,应该阻止用户跳转,结合vuex状态管理(dialogVisibility是否有保存)
beforeRouteLeave (to, from, next) { //判断是否弹出框的状态和保存信息与否 if (this.dialogVisibility === true) { this.dialogVisibility = false //关闭弹出框 next(false) //回到当前页面, 阻止页面跳转 }else if(this.saveMessage === false) { alert('请保存信息后退出!') //弹出警告 next(false) //回到当前页面, 阻止页面跳转 }else { next() //否则允许跳转 } }
应用场景3:保存相关内容到Vuex中或Session中
当用户需要关闭页面时, 可以将公用的信息保存到session或Vuex中
beforeRouteLeave (to, from, next) { localStorage.setItem(name, content); //保存到localStorage中 next() }