单击图像后,我希望按钮显示在图库中的图像下方。这是我的Vue组件的片段:
<div class="col-xs-2" v-for="(data, key) in imgParsed">
<a v-show="data != null" href='javascript:void(0);' @click.prevent="showRemove(key)">
<img :src="data" :alt="key">
</a>
<div class="row" v-show="removingImage[key]">
<div class="col-xs-6">
<a href="javascript:void(0);" class="btn btn-danger right" value="Remove image" @click.prevent="remove(key)">Remove this image</a>
</div>
<div class="col-xs-6">
<a href="javascript:void(0);" class="btn btn-success left" value="Cancel" @click.prevent="hideRemove(key)">Cancel</a>
</div>
</div>
</div>
removingImage
是一个包含图像名称以及是否已单击图像名称的对象。示例(在Vue组件中):
...
data() {
return {
...
removingImage: {
image1: false,
...
imageN: false, // They are all false by default
}
}
}
单击图像时,
showRemove(key)
应该显示确认和取消按钮。这是通过将removingImage[img]
设置为true
来完成的。当按下取消按钮时,
hideRemove(key)
应该隐藏确认和取消按钮。这是通过将removing[img]
设置为false
来完成的问题
调用方法
showRemove("image1")
时,removingImage["image1"]
的值似乎没有响应。答:在Vue Devtools中,除非我重新单击组件详细信息,本质上重新评估组件的状态,否则
removingImage["image1"]
的值保持为false。B.在
showRemove
方法中,我包括以下调试代码:showRemove: function(img) {
try {
var a = this.removingImage[img]
this.removingImage[img] = true; // This was the only thing originally there
var b = this.removingImage[img]
console.log('a = '+a,'b = '+b)
if (a==b && a == false) {console.log('removingImage not updating')}
} catch (err) {
console.log(err)
}
}
单击图像一次会生成
a = false b = true
,然后再次显示a = true b = true
,这告诉我removingImage["image1"]
的值正在更新,但是组件没有“看到它”?C.我在模板中加入了一些胡须(如
{{removeImage[key]}}
),以便可以确认自己的担心。如我所料,无论我单击图像多少次,它始终显示this。有任何想法吗?
编辑:我将尝试重现该问题。
Edit(2):fiddle,如所承诺的(对不起的代码-我对此非常陌生)
最佳答案
嗯,这很奇怪。无论如何,我通过创建一个新对象并重新分配它来使其工作..
showRemove: function (img) {
try {
var a = this.removingImage[img]
this.removingImage = { ...this.removingImage, [img]: true }
var b = this.removingImage[img]
console.log('a = ' + a, 'b = ' + b)
if (a == b && a == false) {
console.log('removingImage not updating')
}
} catch (err) {
console.log(err)
}
}
Fiddle
要么
showRemove: function (img) {
try {
var a = this.removingImage[img]
this.removingImage = Object.assign({}, this.removingImage, { [img]: true })
var b = this.removingImage[img]
console.log('a = ' + a, 'b = ' + b)
if (a == b && a == false) {
console.log('removingImage not updating')
}
} catch (err) {
console.log(err)
}
}
Fiddle
另外,您可以使用
$forceUpdate
..showRemove: function (img) {
try {
var a = this.removingImage[img]
Vue.set(this.removingImage, img, true)
var b = this.removingImage[img]
console.log('a = ' + a, 'b = ' + b)
if (a == b && a == false) {
console.log('removingImage not updating')
}
this.$forceUpdate()
} catch (err) {
console.log(err)
}
}
Fiddle