我想访问外部函数中的 vue 实例(debounce)。然而,这指向窗口对象。我怎样才能改变上下文? 目前,它指向对象“window”,但我想访问 vue“data”
这是我的例子
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>
最佳答案
解决方案是使用“普通”函数而不是箭头函数,如下所示:
resizeMedia: debounce(function() {
// logs the vue instance
console.log(this);
}, 250),
},
关于javascript - 更改对 vue 实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503919/