当vue与axios直接在html文件中使用的时候,位于axios的请求中的this指向并不是指向vue,而是指向window,如果在请求中直接用this获取data中的数据会出现undefined的问题,解决思路是将ES5的函数语法更换为箭头函数即可解决此问题,深层的原因就得深入去了解箭头函数和普通函数之间的区别了!
案例:
new Vue {
axios.get.then {
// 这里的this.carousels是undefined,因此上下边的赋值是不起作用的
this.carousels = res.data
}).catch {
console.log
});
},
})
以上案例可以发现在axios中使用this获取data中的值是获取不到的,这就是this的指向问题造成的,他不是指向vue , 只需要修改如下,将function函数改为箭头函数即可解决!
修改代码如下:
new Vue {
axios.get.then.catch
});
},
})
到此问题就解决了!
pgc-card .pgc-card-href:hover {text-decoration: none;}/*pc 样式*/.pgc-card {box-sizing: border-box;height: 164px;border: 1px solid e8e8e8;height: 120px;position: absolute;right: 76px;top: 20px;}.pgc-cover {position: absolute;width: 162px;height: 162px;top: 0;left: 0;background-size: cover;}.pgc-content {overflow: hidden;position: relative;top: 50%;-webkit-transform: translateY;transform: translateY;}.pgc-content-title {font-size: 18px;color: 444;overflow: hidden;text-overflow: ellipsis;padding-top: 9px;overflow: hidden;line-height: 1.2em;display: -webkit-inline-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}.pgc-content-price {font-size: 22px;color: 406599;font-size: 14px;text-align: center;}.pgc-buy-text {padding-top: 10px;}.pgc-icon-buy {height: 23px;width: 20px;display: inline-block;background: url;}Vue.js开发与项目实战¥69购买
【vue在html中结合axios时,this指向为undefined解决办法】以上就是朝夕生活(www.30zx.com)关于“vue在html中结合axios时,this指向为undefined解决办法”的详细内容,希望对大家有所帮助!
猜你喜欢
- 如何解决 JavaScript 中处理 null 和 undefined 的麻烦事
- this 设计缺陷和应对方案
- 香水排行榜前十名男士:博宝利英伦迷情上榜,第一无比强烈
- PHP的Undefined variable错误怎么解决?
- 一文搞定递归、非递归的左右互搏术
- JavaScript中解决堆栈溢出,简单的方法是将堆栈调用改成事件循环
- 安卓用户注意:微信闪退、无响应,使用这个方法有效避免
- CF手游微信登录不了 微信登录失败解决方法
- 手机APP经常弹出“无响应”?可以尝试这几个方法
