Solution to the problem in vue2 that this of the nested method in the method method does not point to the vue instance

question structure

Similar to nested functions, the function movePlane method uses this.app internally. Note that this written in this way is not a vue instance, and an exception will be reported that the app cannot be found.

export default {
    
    
  data() {
    
    
    return {
    
    
      app:null,
    }
  },
  methods: {
    
    
    // 游戏窗体加载
    initPixi() {
    
    
      function movePlane(event) {
    
    
        if (isStart) {
    
    
          var pos = event.data.getLocalPosition(this.app.stage)
          plane.x = pos.x
          plane.y = pos.y - 70
        }
      }
    }

problem solved

      movePlane = movePlane.bind(this);

Use the bind method to bind this to the movePlane method

export default {
    
    
  data() {
    
    
    return {
    
    
      app:null,
    }
  },
  methods: {
    
    
    // 游戏窗体加载
    initPixi() {
    
    
      function movePlane(event) {
    
    
        if (isStart) {
    
    
          var pos = event.data.getLocalPosition(this.app.stage)
          plane.x = pos.x
          plane.y = pos.y - 70
        }
      }
      
      movePlane = movePlane.bind(this);
    }

Guess you like

Origin blog.csdn.net/qq_39123467/article/details/131852274