setTimeout中的this指向问题

2018-10-23  本文已影响0人  索伯列夫
var app = new Vue({
  el: '#app',
  data: {
    msg: '不要管',
    date: new Date(),
    name: 'huahua',
    age: '<p>28</p>',
    change: 'red',
    number: 1000
  },
  methods: {
    count: function() {
      console.log(this)
      this.number += 1
    }
  },
  filters: {
    filter: function() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDay()
      let sec = date.getSeconds()
      return year + '-' + month + '-' + day + '-' + sec
    }
  },
  mounted: function() {
    //注意setInterval中的this指向
    setInterval(function(){
      this.date = new Date()  //错误!
    }, 1000)
  }
})

在这段代码中,this指向window

mounted: function() {
    //注意setInterval中的this指向
    setInterval(function(){
      this.date = new Date()  //错误!
    }, 1000)
  }

改正: (让this指向vue实例)
一、借助变量保存this

mounted: function() {
    //注意setInterval中的this指向
    let _this = this
    setInterval(function(){
      _this.date = new Date()  //错误!
    }, 1000)
  }

二、利用箭头函数
使用es6中的箭头函数,因为在箭头函数中this是固定的。
箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。

mounted: function() {
    //注意setInterval中的this指向
    setInterval(()=>{
      this.date = new Date()  //错误!
    }, 1000)
  }
上一篇 下一篇

猜你喜欢

热点阅读