vue的method方法如何将vm实例的this传进子函数中

在以下代码环境中应该如何修改seen值。已经试过这些方法
1、首先seen是可以用实例调用,代码中用this.seen表示。但是在下面情况下this指向已经发生改变,用this.seen无法改变
2、在函数外部将this赋值给that的方法也不行 不过我的用法可能有问题 请大神指点
3、用箭头函数。会报错Cannot read property 'seen' of undefined

<div>{{seen}}</div>

export default {
  data() {
    return {
      seen: '数据'
    }
  },
  components: {
  },
  methods: {
    a:function() {
       bulabulabula
       xmlhttp.onreadystatechange = function (that) {
          if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            xxx.seen = true 
            }
       }
    }
  }
}

查了好多资料都没找到方法求大神指点

阅读 4.4k
3 个回答
export default {
  data() {
    return {
      seen: '数据'
    }
  },
  components: {
  },
  methods: {
    a:function() {
       const that = this;
       xmlhttp.onreadystatechange = function () {
          if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
               that.seen = true 
            }
       }
       //箭头函数
       //xmlhttp.onreadystatechange = () => {
         // if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
           //    this.seen = true 
            //}
       //}
    }
  }
}

箭头函数本身没有this,都是外面的,应该是可以的,我也一直这么用的。你那个报错的代码贴出来看看。

1:你打印下this的值,此时this的值应该发生改变;定义一个局部变量来接收let that = this

2:你最好引入ajax,http请求已经封装好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题