美文网首页
setTimeout中的this指向问题

setTimeout中的this指向问题

作者: 索伯列夫 | 来源:发表于2018-10-23 18:27 被阅读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)
      }
    

    相关文章

      网友评论

          本文标题:setTimeout中的this指向问题

          本文链接:https://www.haomeiwen.com/subject/oxnazftx.html