Vue--this的指代问题及用法

Vue--this的指代问题及用法

  • this在普通函数( function( ){ } )里,指代调用该函数(方法)的对象
  • this在箭头函数( ()=>{} )里,指代定义该箭头函数的外层对象

在axios调用当前vue实例的data:

  • axios回调函数( .then() )是在执行栈中被执行,其中this指向window,若要在axios中取后端数据并赋值给data,2种方法
    1. 回调函数内部改为箭头函数,this指向由window转为定义箭头函数外层对象即该vue实例
    2. 在函数内axios外定义临时变量保存当前vue实例,var that=this,在.then()中使用that即可
created: function () {
        var that=this
        axios({
            url: 'http://localhost:8088/api/Statistics',
            method: 'get',
            params: {
                user_id: that.$store.state.user_id //windows访问不了store
            }
        })
            .then(response=>{
                this.total=response.data[0],
                this.done=response.data[1],
                this.rest=response.data[2],
                this.today=response.data[3]
            })
    }
  • 特别地,created(),mounted(),destroyed()等实例生命周期的钩子函数的this指向该vue实例
posted @ 2023-09-14 22:37  chuimber  阅读(261)  评论(0)    收藏  举报