UNPKG

@ylz/plugins

Version:

ylz plugins

78 lines (76 loc) 2.21 kB
const routerThen = { $router: null, resolve: null, // 跳到指定页面,并返回promise request: function(requestType = 'push', location, onComplete = null, onAbort = null) { if (!location || location === '') { throw new Error('location is missing') } return new Promise((resolve, reject) => { if (this.$router) { this.resolve = resolve switch (requestType) { case 'push': this.$router.push(location, onComplete, onAbort) break case 'replace': this.$router.replace(location, onComplete, onAbort) break case 'go': this.$router.go(location) break default: reject(new Error('requestType error:' + requestType)) break } } else { reject(new Error('$router missing')) } }).catch((error) => { this.resolve = null throw new Error(error) }) }, // 前往指定页面 push: function(location, onComplete = null, onAbort = null) { return this.request('push', location, onComplete, onAbort) }, // 替换当前页 replace: function(location, onComplete = null, onAbort = null) { return this.request('replace', location, onComplete, onAbort) }, // 历史记录跳转 go: function(step = 0) { return this.request('go', step) } } export default { install: function(Vue, { router }) { routerThen.$router = router Object.defineProperty(Vue.prototype, '$routerThen', { value: routerThen }) Vue.mixin({ // 在路由跳转到下一个页面之前,为下一个页面注册回调事件。 beforeRouteEnter: function(to, from, next) { if (routerThen.resolve) { next((vm) => { try { routerThen.resolve(vm) routerThen.resolve = null } catch (error) {} }) } else { next() } }, beforeRouteUpdate: function(to, from, next) { if (routerThen.resolve) { try { routerThen.resolve(this) routerThen.resolve = null } catch (error) {} } next() } }) } }