javascript - 将此引用更改为 vue 实例
问题描述
我想在外部函数(去抖动)中访问 vue 实例。然而这指向窗口对象。我怎样才能改变上下文?目前,这指向对象“窗口”,但是我想进入 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>
解决方案
一个解决方案是,使用“普通”函数而不是箭头函数,如下所示:
resizeMedia: debounce(function() {
// logs the vue instance
console.log(this);
}, 250),
},
推荐阅读
- c# - 为什么 C# 编译器使用隐式运算符返回的值的父类型来调用重载运算符
- angular - 如何在 Kendo Angular multiselectBox 中实现选择和取消选择事件
- r - 使用 sapply 列出向量的所有部分,但不在底部显示列表
- python - 基数为 10 的 int() 的无效文字:'1,265'
- python - pywinauto 键盘.sendkeys()。发送相当于同时按住几个键
- .net - 为什么 Visual Studio 安装程序将一些依赖项放入不作为依赖项?
- makefile - make:指定包依赖位置
- javascript - history.push('/somePath') 不工作,被异步函数弄糊涂了
- .net - .NET - Microsoft.Web.WebView2 是开源的吗?
- flutter - 在更新我的应用程序时,您的 Android App Bundle 使用错误的密钥签名错误