当vue与axios直接在html文件中使用的时候,位于axios的请求中的this指向并不是指向vue,而是指向window,如果在请求中直接用this获取data中的数据会出现undefined的问题,解决思路是将ES5的函数语法更换为箭头函数即可解决此问题,深层的缘由就得深入去了解箭头函数和普通函数之间的区别了!

案例:
new Vue({
el: '#app',
data:{
carousels: [],
},
created() {
axios.get('/api/banners/').then(function (response) {
// 这里的this.carousels是undefined,因此上下边的赋值是不起作用的
this.carousels = res.data
}).catch(function (error) {
console.log(err)
});
},
})
以上案例可以发目前axios中使用this获取data中的值是获取不到的,这就是this的指向问题造成的,他不是指向vue,只需要修改如下,将function函数改为箭头函数即可解决!
修改代码如下:
new Vue({
el: '#app',
data:{
carousels: [],
},
created() {
axios.get('/api/banners/').then(res => {
this.carousels = res.data
}).catch(err => {
console.log(err)
});
},
})
到此问题就解决了!
#pgc-card .pgc-card-href { text-decoration: none; outline: none; display: block; width: 100%; height: 100%; } #pgc-card .pgc-card-href:hover { text-decoration: none; } /*pc 样式*/ .pgc-card { box-sizing: border-box; height: 164px; border: 1px solid #e8e8e8; position: relative; padding: 20px 94px 12px 180px; overflow: hidden; } .pgc-card::after { content: ” “; display: block; border-left: 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(-50%); transform: translateY(-50%); } .pgc-content-title { font-size: 18px; color: #222; line-height: 1; font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pgc-content-desc { font-size: 14px; 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: #f85959; padding-top: 18px; line-height: 1em; } .pgc-card-buy { width: 75px; position: absolute; right: 0; top: 50px; 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(https://lf3-cdn-tos.bytescm.com/obj/cdn-static-resource/pgc/v2/pgc_tpl/static/image/commodity_buy_f2b4d1a.png); }
Vue.js开发与项目实战
¥69
购买
<script src=”//mp.toutiao.com/mp/agw/mass_profit/pc_product_promotions_js?item_id=6998682101717434892″></script>