从Vue.js手表中获取反应
问题描述:
尝试在Vue.js中创建一个组件,该组件首先通过缩略图显示图像,在后台加载完整图像以及加载时显示完整图像。从Vue.js手表中获取反应
不工作的东西,组件在show section的showThumb标志的变化上没有反应。哪里不对?
Vue.component('page-image',
{
props: ['data'],
template:
'<img v-if="showThumb == true" v-bind:src="thumbSrc"></img>'+
'<img v-else v-bind:src="fullSrc"></img>',
data: function()
{
return { thumbSrc: '', fullSrc: '', showThumb: true };
},
watch:
{
data: function()
{
this.thumbSrc = data.thumbImg.url;
this.fullSrc = data.fullImg.url;
this.showThumb = true;
var imgElement = new Image();
imgElement.src = this.fullSrc;
imgElement.onload = (function()
{
this.showThumb = false; // <<-- this part is broken
});
}
}
});
注:有一个原因,我通过2个img标签 - 这个例子是简化的。
答
您的onload
回调将具有与周围的手表功能不同的范围,因此您无法像这样设置数据属性。它变成一个箭头功能,以保持范围:
imgElement.onload =() =>
{
this.showThumb = false;
};
见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
在我身边
愚蠢的错误......非常感谢! – iburyl