Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

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

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中却没有发生变化是什么原因?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

第一个问题
箭头函数内的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调的。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...