Vue2的回调函数中this失效

源头

最近在使用vue开发H5的项目前端的时候,遇见了内置回调函数function中无法使用this的情况。

业务逻辑

  • 1、获取用户信息。
  • 2、将获取到的用户信息赋值给全局用户变量。

程序

<template>
  <div class="hello">
    <el-row style="margin-top:10px;">
      <el-col :span="12">
        <el-button type="primary" @click="doClickForGetUserInfo">获取值</el-button>
      </el-col>
    </el-row>
  </div>
</template>
  
<script>
  export default {
    name: 'HelloWorld1',
    data () {
      return {
        pubUserInfo: {},
      }
    },
    watch: {},
    mounted() {},
    created() { 
      this.firstLoaded();
    },
    methods: {
      doClickForGetUserInfo() {
        alert("用户信息 = " + JSON.stringify(this.pubUserInfo));
      },

      firstLoaded() {
        this.getUserInfo(function(userInfoParam) {
          this.pubUserInfo = userInfoParam;
        });
      },

      getUserInfo(successCallback) { // 获取用户信息
        successCallback({"name" : "sunpy", "address" : "吉林"});
      },
    }
  }
</script>
<style scoped></style>
  • 测试结果

image

解决办法

firstLoaded() {
    let tempThis = this;
    this.getUserInfo(function(userInfoParam) {
      tempThis.pubUserInfo = userInfoParam;
    });
},

image

分析不同情况下this的作用域

第1种,在javascript文件中引用this

## test.js
export function doMethod() {
    console.log(this);
}

## vue文件
import { doMethod } from '../utils/test.js';

doClickForGetUserInfo() {
    doMethod();
},

结果:this为undefined

image

第2种,methods中的this

doClickForGetUserInfo() {
    console.log(this);
},

结果:this指向当前组件的实例

image

第3种,内部箭头函数中的this

doClickForGetUserInfo() {
    this.getUserInfo((data) => {
      console.log(this);
    });
},

getUserInfo(successCallback) { // 获取用户信息
    successCallback({"name" : "sunpy", "address" : "吉林"});
}

结果:this指向当前组件的实例

image

第4种,内部函数function中的this

doClickForGetUserInfo() {
    this.getUserInfo(function(data) {
      console.log(this);
    });
},

结果:this为undefined

image

posted @ 2025-05-25 11:26  sunpeiyu  阅读(6)  评论(0)    收藏  举报