问答

vue中使用箭头函数this指向发生了变化?

作者:admin 2021-05-12 我要评论

getData (data) { let self = this this.$axios.post('http://xxx.net:8092/quotes/retrieve', data).then(res = { console.log(this) //console 输出undefined ...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
getData (data) {
      let self = this
      this.$axios.post('http://xxx.net:8092/quotes/retrieve', data).then(res => {
        console.log(this)  //console 输出undefined
        const { r_data}  = res.data
        self.curRic = data
        self.ricData = r_data
        this.$forceUpdate()
      })
    },

使用this赋值curRic和ricData失败,输出this发现是undefined,明明使用的是箭头函数为什么会出现这种情况?
我换成self,发现可以赋值成功,但是template中却没有发生变化是什么原因?

###

第一个问题
箭头函数内的this自动指向了回调函数外层的 this 。(实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。正是因为它没有 this,所以也就不能用作构造函数。)
像这样的

this.$nextTick(()=>{
    console.log(this)  //指向了回调函数外层的 this       
});

this.setTimeout(()=>{
    console.log(this)   //指向了回调函数外层的 this    
},500);

然而你这样,this 输出 undefined

this.$axios.post().then(res => {
    console.log(this)  //console 输出undefined
});

then() 是异步的回调函数,this指向早变了。具体怎么变化的需要再研究一下。

第二个问题
页面没变化是因为你那个强制页面更新的函数还是用this调的。。

###

我表示质疑...
Vue methods里面的方法都是绑定实例的,方法中定义的箭头函数,this自然指向实例。
可以贴完整代码吗?

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • vue中使用箭头函数this指向发生了变化

    vue中使用箭头函数this指向发生了变化

  • gitee有办法触发github的action/workfl

    gitee有办法触发github的action/workfl

  • 为何网页上显示的dom元素,放入闭包的数

    为何网页上显示的dom元素,放入闭包的数

  • 某工程的依赖A中排除另一个依赖B,再在

    某工程的依赖A中排除另一个依赖B,再在

腾讯云代理商
海外云服务器