我想访问外部函数中的vue实例(去抖动)。但是,这指向窗口对象。如何更改上下文? 目前,它指向对象“窗口”,但是我想了解“数据”
这是我的例子
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>
答案 0 :(得分:2)
一种解决方案是,使用“正常”功能代替箭头功能,如下所示:
resizeMedia: debounce(function() {
// logs the vue instance
console.log(this);
}, 250),
},