vue router 里push方法重写为什么要重绑定this
Vue Router 的push
方法依赖this
Vue Router 的push
方法内部通过this
访问关键属性(如this.history
):
// Vue Router内部简化实现
VueRouter.prototype.push = function(location) {
// 依赖this访问路由历史和配置
return this.history.push(location);
};
当你重写push
时,若直接调用:
let origin = VueRouter.prototype.push
VueRouter.prototype.push = function (location, reslove, reject) {
if (reslove && reject) {
origin(this,location, reslove, reject)
}
else {
origin(this,location, () => { }, () => { })
}
}
this
会指向全局对象(如window
)或undefined
(严格模式),导致this.history
报错。
所以需显式将this
绑定为 Vue Router 实例,确保this.history
正确指向路由历史。
即:
let origin = VueRouter.prototype.push
VueRouter.prototype.push = function (location, reslove, reject) {
if (reslove && reject) {
origin.call(this,location, reslove, reject)
}
else {
origin.call(this,location, () => { }, () => { })
}
}