首页 > 解决方案 > 将此引用更改为 vue 实例

问题描述

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

这是我的例子

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>

标签: javascriptvue.jsthisdebounce

解决方案


一个解决方案是,使用“普通”函数而不是箭头函数,如下所示:

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

推荐阅读