发现当动态修改当前页面的url中的query时会报错
是因为新创建的路由不能使用老路由的对象,而应该重新创建一个对象,以解决问题
报错内容
新老路由发生重复,停止跳转
解决方法
// 首先获取当前url
const q = this.$route && this.$route.query
// 通过创建新的路由的方式来添加参数
this.$router.push({ query: Object.assign({ filename: '' }, q) })
原因
-
查看
Vue-Router
的源码,发现其判断的是新老query
对象是否完全一致。 -
而当通过直接修改
$route.query
去变化页面的时候,将会使得老的query
对象也会跟着一起改变,于是就会被报路由重复
-
Vue-Router
的源码中关于新老的判断-
function isSameRoute (a, b, onlyPath) { if (b === START) { return a === b } else if (!b) { return false } else if (a.path && b.path) { return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath || a.hash === b.hash && isObjectEqual(a.query, b.query)) } else if (a.name && b.name) { return ( a.name === b.name && (onlyPath || ( a.hash === b.hash && isObjectEqual(a.query, b.query) && isObjectEqual(a.params, b.params)) ) ) } else { return false } }
-
-
关于路由更新的逻辑
-
if ( isSameRoute(route, current) && // in the case the route map has been dynamically appended to lastRouteIndex === lastCurrentIndex && route.matched[lastRouteIndex] === current.matched[lastCurrentIndex] ) { this.ensureURL(); if (route.hash) { handleScroll(this.router, current, route, false); } return abort(createNavigationDuplicatedError(current, route)) }
-
在
abort(createNavigationDuplicatedError(current, route))
处弹出报错
-
实战实例
<script>
mounted () {
const q = this.$route && this.$route.query
const fn = q && q.filename
if (fn) {
this.fileName = fn
this.component = 'Viewer'
} else {
this.component = 'Editor'
if (q.filename === undefined) { this.$router.push({ query: Object.assign({ filename: '' }, q) }) }
}
}
</script>