vue里面的this指向变了,有几种能代替全局this方法?

methods: {

// 下拉刷新回调
pullupRefresh () {
  var _this = this
  setTimeout(function () {
    _this.add()
    // 停止刷新
    _this.mui('#pullrefresh').pullRefresh().endPulldownToRefresh()
  }, 1500)
},
pulldownRefresh () {
  var _this = this
  setTimeout(function () {
    _this.mui('#pullrefresh').pullRefresh().endPullupToRefresh(_this.count >= _this.isNumber)
    _this.add()
    // 小于数据的长度 提示
    if (_this.count <= Math.floor(_this.chartList.length / 5)) {
      _this.mui.toast("为你推荐了5篇文章")
    }
  }, 1500);
},
add () {
  this.count += 1
  // 截取5个数据
  this.newArr = this.chartList.slice((this.count - 1) * 5, (this.count - 1) * 5 + 5)
  var box = document.getElementById("pullName")
  // 获取box的style属性用作判断
  var styleList = window.getComputedStyle(box)
  console.log(this.count, 4455)
  if (this.count <= 10/5) {
    // 首次加载10条数据
    this.arr = this.chartList.slice(0, 10)
  } else if (styleList.transform.indexOf('50') !== -1) {
    // 下拉执行向数组头部添加
    this.arr.unshift.apply(this.arr, this.newArr)
  } else {
    // 上拉加载向数组后面添加
    this.arr.push.apply(this.arr, this.newArr)
  }
  this.isNumber = Math.floor(this.chartList.length / 5)
}

}
}

上面的使用vue+mui的有的时候this指向会发生变化,但是不想用var _this = this来把全局赋给一个变量,
有没有其他方法!我用过Window,document,不行!!

阅读 12.8k
6 个回答

不用 that = this 的话,最好的方法就用bind了,
understanding-javascript-function-prototype-bind

可以参考下这种写法 把setTimeout 里面的函数提出来

var obj = {a:1};

obj.fn2 = function(){console.log(this)}

obj.fn = function(){setTimeout(this.fn2.bind(this),300)}

obj.fn()   // 这里的this 就指向了obj  了

用箭头函数呗

还有一个很好的办法,一般初始化Vue实例的时候都是直接new Vue({...}),但也可以这么写:

var app = new Vue({...});

这样在里面的数据可以通过app.data之类的能获取到,应该说整个实例包含的内容都能获取到。

一般情况下,使用箭头函数this的指向和外层的this相同,但是你涉及到setTimeout,环境发生变化,使用_this = this是正确的做法,没什么的大碍的

不知道你不想用var _this = this的原因和想法从何而来 我基本没见过vue 项目会不用这样拿到 vue实例的指向的

最好用箭头函数了
setTimeout(()=>{

//this...
}

}, 1500);

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