鍍金池/ 問答/HTML5  HTML/ vue里面的this指向變了,有幾種能代替全局this方法?

vue里面的this指向變了,有幾種能代替全局this方法?

methods: {

// 下拉刷新回調(diào)
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()
    // 小于數(shù)據(jù)的長度 提示
    if (_this.count <= Math.floor(_this.chartList.length / 5)) {
      _this.mui.toast("為你推薦了5篇文章")
    }
  }, 1500);
},
add () {
  this.count += 1
  // 截取5個數(shù)據(jù)
  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條數(shù)據(jù)
    this.arr = this.chartList.slice(0, 10)
  } else if (styleList.transform.indexOf('50') !== -1) {
    // 下拉執(zhí)行向數(shù)組頭部添加
    this.arr.unshift.apply(this.arr, this.newArr)
  } else {
    // 上拉加載向數(shù)組后面添加
    this.arr.push.apply(this.arr, this.newArr)
  }
  this.isNumber = Math.floor(this.chartList.length / 5)
}

}
}

上面的使用vue+mui的有的時候this指向會發(fā)生變化,但是不想用var _this = this來把全局賦給一個變量,
有沒有其他方法!我用過Window,document,不行!!

回答
編輯回答
傲寒

一般情況下,使用箭頭函數(shù)this的指向和外層的this相同,但是你涉及到setTimeout,環(huán)境發(fā)生變化,使用_this = this是正確的做法,沒什么的大礙的

2017年2月18日 21:17
編輯回答
骨殘心

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

可以參考下這種寫法 把setTimeout 里面的函數(shù)提出來

var obj = {a:1};

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

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

obj.fn()   // 這里的this 就指向了obj  了
2018年5月26日 13:35
編輯回答
初心

不知道你不想用var _this = this的原因和想法從何而來 我基本沒見過vue 項目會不用這樣拿到 vue實例的指向的

2017年5月16日 09:59
編輯回答
伐木累

最好用箭頭函數(shù)了
setTimeout(()=>{

//this...
}

}, 1500);

2018年5月10日 19:57
編輯回答
殘淚

用箭頭函數(shù)唄

2017年11月15日 13:27
編輯回答
熊出沒

還有一個很好的辦法,一般初始化Vue實例的時候都是直接new Vue({...}),但也可以這么寫:

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

這樣在里面的數(shù)據(jù)可以通過app.data之類的能獲取到,應(yīng)該說整個實例包含的內(nèi)容都能獲取到。

2018年2月1日 22:35