• vue 中的this问题


    在vue中当在vue中使用匿名函数的时候,会出现this指针改变的问题,出现方法或者属性数据undefine的问题,以下是相关的解决方法
    一、在回调函数之前重新将this赋值
    例如

     connection() {
          // 更换that指针
          var that = this
          const socket = new SockJS('http://localhost:8080/test-info')
          this.stompClient = Stomp.over(socket)
          console.log('----------------')
          console.log(this.stompClient)
          console.log('----------------')
          const tt = this.stompClient
          // 此处不能使用 this.stompClient
          tt.connect({}, function(frame) {
            console.log('++++++++++++++++')
            console.log('Connected: ' + frame)
            console.log('++++++++++++++++')
    
            tt.subscribe('/stock/price', function(val) {
              console.log(val)
              console.log(JSON.parse(val.body))
              that.list1 = JSON.parse(val.body)
            })
          })
        }
    

    二、使用箭头函数

      connection() {
          // 更换that指针
          const socket = new SockJS('http://localhost:8080/test-info')
          this.stompClient = Stomp.over(socket)
          console.log('----------------')
          console.log(this.stompClient)
          console.log('----------------')
           this.stompClient.connect({}, (frame) => {
            console.log(frame)
            this.stompClient.subscribe('/stock/price', (val) => {
              console.log('--------list1-----------')
              console.log(this.list1)
              console.log('--------list1-----------')
              this.list1 = JSON.parse(val.body)
            })
          })
        }
    

    在回调函数中有时候回调函数会修改this的指向,this本来应该指的是vue这个对象,但是他的this指向的是回调,由于在回调函数改变了this指针,导致后序出现this指向的数据出现未定义的状况。
    但是在箭头函数中this指向的永远都是vue对象,所以建议多是想用箭头函数



    作者:jianshuqiang
    链接:https://www.jianshu.com/p/cc2c36513066
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    原子核结构壳模型:粒子空穴转换
    第十二周学习总结
    构建之法读书笔记5
    5.21学习总结——android开发实现用户头像的上传
    5.20团队活动
    构建之法读书笔记4
    团队项目第一阶段验收
    HTML+CSS设计个人主页
    C++文件流
    面向对象程序设计_虚函数的应用
  • 原文地址:https://www.cnblogs.com/songjuntao/p/16168045.html
Copyright © 2020-2023  润新知