将此引用更改为 vue 实例

change this reference to vue instance

我想在外部函数中访问 vue 实例(去抖动)。然而,这指向 window 对象。我怎样才能改变上下文? 目前这是指向对象 "window" 但是我想去 vue "data"

这是我的例子

jsfiddle

var debounce = function(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

new Vue({
  el: "#app",
  data: {
    media: 'phone'
  },
  methods: {
   resizeMedia: debounce((e) => {
          console.log('resize debounce');
              
          //here vue this?
                this.media = window
                .getComputedStyle(
                document.querySelector('#app'), ':before')
                               .getPropertyValue('content')
                               .replace(/\"/g, '');
                
    },250),
  },
  mounted: function () {
      window.addEventListener('resize',  this.resizeMedia)
  },
  beforeDestroy: function () {
      window.removeEventListener('resize', this.resizeMedia)
  },
})
body {
  background: #ccc;
  padding: 20px;
}
body:before {
      content: "small-phone";
}
@media (min-width: 200px) {
    body:before {
      content: "phone";
    }
}
@media (min-width: 300px) {
    body:before {
      content: "tablet";
    }
}
@media (min-width: 400px) {
    body:before {
      content: "desktop";
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ media }}
</div>

一个解决方案是,使用 "normal" 函数而不是箭头函数,如下所示:

resizeMedia: debounce(function() {
  // logs the vue instance
  console.log(this);               
 }, 250),
},