我希望在单击图像时按钮显示在图库中的图像下方。这是我的 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]}}
这样我就可以证实我的恐惧。正如我所料,无论我点击图像多少次,它总是会显示这一点。
有什么想法吗?
编辑:我将尝试在小提琴中重现问题。
编辑(2(:小提琴,正如承诺的那样(请原谅恶心的代码 - 我对此非常陌生(
嗯,这很奇怪。无论如何,我通过创建一个新对象并重新分配它来让它工作..
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)
}
}
小提琴
或
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)
}
}
小提琴
或者,您可以使用$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)
}
}
小提琴
使用
Vue.set()
https://v2.vuejs.org/v2/guide/reactivity.html
例:
Vue.set(this.removingImage, img, true)