我遇到了以下问题,我不知道该如何正确解决。
我在视图中“列出”了所有购买的图像。我用v-for循环显示它们。每个图像还具有进度条元素,因此,当用户单击下载按钮时,将执行downloadContent功能,并应显示进度条。
所以我的html看起来像这样。
<section class="stripe">
<div class="stripe__item card" v-for="(i, index) in purchasedImages">
<progress-bar :val="i.download_progress"
v-if="i.download_progress > 0 && i.download_progress < 100"></progress-bar>
<div class="card__wrapper">
<img :src="'/'+i.thumb_path" class="card__img">
</div>
<div class="btn-img card__btn card__btn--left" @click="downloadContent(i.id_thumb, 'IMAGE', index)">
</div>
</div>
</section>
这是我的JS代码
import Vue from 'vue'
import orderService from '../api-services/order.service';
import downloadJs from 'downloadjs';
import ProgressBar from 'vue-simple-progress';
export default {
name: "MyLocations",
components: {
ProgressBar: ProgressBar
},
data() {
return {
purchasedImages: {},
purchasedImagesVisible: false,
}
},
methods: {
getUserPurchasedContent() {
orderService.getPurchasedContent()
.then((response) => {
if (response.status === 200) {
let data = response.data;
this.purchasedImages = data.images;
if (this.purchasedImages.length > 0) {
this.purchasedImagesVisible = true;
// Set download progress property
let self = this;
this.purchasedImages.forEach(function (value, key) {
self.purchasedImages[key].download_progress = 0;
});
}
}
})
},
downloadContent(id, type, index) {
let self = this;
orderService.downloadContent(id, type)
.then((response) => {
let download = downloadJs(response.data.link);
download.onprogress = function (e) {
if (e.lengthComputable) {
let percent = e.loaded / e.total * 100;
let percentage = Math.round(percent);
if (type === 'IMAGE') {
// Is this proper way to set one field reactive?
self.purchasedImages[index].download_progress = percentage;
if (percentage === 100) {
self.purchasedImages[index].download_progress = 0;
}
}
}
}
})
},
},
mounted: function () {
this.getUserPurchasedContent();
}
};
问题是。当用户单击下载按钮时,下载开始执行,并且我获得了下载的内容,但是看不到进度栏。所以我想知道,这是设置元素反应性的正确方法吗?我的实现应如何?如何正确设置self.purchasedImages[index].download_progress
对象键值,以便进度条可见?
如果您需要任何其他信息,请告诉我,我会提供。谢谢!
答案 0 :(得分:4)
摘要:
this.purchasedImages = data.images;
使我们相信data.images
是没有download_progress
属性的对象数组。因此,Vue在更改时无法检测/反应。
要解决此问题,您可以使用Vue.set
:
Vue.set(self.purchasedImages[key], 'download_progress', 0);
这在Vue.js docs中有很好的解释。
data
之前添加属性仅出于完整性考虑,您还可以添加download_progress
之前 ,将数组分配给data
属性。这将使Vue注意到它并能够对其做出反应。
示例:
let data = response.data;
this.purchasedImages = data.images.map(i => ({...i, download_progress: 0}));
if (this.purchasedImages.length > 0) {
this.purchasedImagesVisible = true;
// no need to set download_progress here as it was already set above
}
// if above could also be simplified to just:
this.purchasedImagesVisible = this.purchasedImages.length;
另一方面,由于它将成为数组而不是对象,因此我建议您这样声明:
data() {
return {
purchasedImages: [], // was: {},
这将无效,因为您在(purchasedImages
)中完全覆盖了this.purchasedImages = data.images;
,但这是一个好习惯,因为它记录了属性的类型。