Vue.js中调用this.$router.push时出现$router undefined错误是什么原因?
问题原因
错误本质是this指向偏移:你在axios的then回调中使用了普通函数声明,普通函数的this会在执行时根据调用上下文绑定,此处回调执行时this不再指向Vue实例,而是指向全局对象(严格模式下为undefined),因此无法读取到挂载在Vue实例上的$router属性。
解决方案
以下是三种常用的修复方案,任选一种即可:
方案1:使用箭头函数(最推荐)
箭头函数不会绑定独立的this,会继承外层作用域的this指向,直接替换回调的普通函数声明即可:
login: function () { var data = JSON.stringify({ userName: "8801714015073", password: "123456", }); var config = { method: "post", url: "http://192.168.8.14:8080/api/v1/auth/login", headers: { "Content-Type": "application/json", }, data: data, }; this.$axios(config) .then((response) => { console.log(JSON.stringify(response.data)); if (response) { this.$router.push({ name: "Home" }); } }) .catch((error) => { console.log(error); }); }
方案2:提前缓存Vue实例指向
在回调外层提前把Vue实例的this缓存为变量,回调内直接调用该变量即可:
login: function () { const _this = this var data = JSON.stringify({ userName: "8801714015073", password: "123456", }); var config = { method: "post", url: "http://192.168.8.14:8080/api/v1/auth/login", headers: { "Content-Type": "application/json", }, data: data, }; this.$axios(config) .then(function (response){ console.log(JSON.stringify(response.data)); if (response) { _this.$router.push({ name: "Home" }); } }) .catch(function (error) { console.log(error); }); }
方案3:使用bind绑定this指向
通过bind方法手动将回调的this绑定为外层的Vue实例:
this.$axios(config) .then(function (response){ console.log(JSON.stringify(response.data)); if (response) { this.$router.push({ name: "Home" }); } }.bind(this)) .catch(function (error) { console.log(error); });
内容的提问来源于stack exchange,提问作者alprazolam
相关产品推荐
相关产品推荐

