首页 > 投稿专栏 >

undefined怎么解除(undefined解决办法)

73309

方应 分享

时间:

浏览:0

当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)       });     }, })

到此问题就解决了!

本站部分文章来自网络或用户投稿。涉及到的言论观点不代表本站立场。阅读前请查看【免责声明】发布者:方应,如若本篇文章侵犯了原著者的合法权益,可联系我们进行处理。本文链接:https://m.sxhanhai.com/tougao/73309.html

上一篇:win10删除文件提示需要权限怎么办(电脑删除权限的处理方法)

下一篇:win10 ie浏览器在哪(win10系统设置默认浏览器步骤)

相关推荐

热门图文