【发布时间】:2017-02-09 21:19:46
【问题描述】:
我正在尝试在 Vue.js 中构建一个可重用的 Image Loader 组件,它应该:
- 管理自己的缩略图数据
- 以父级的
src为道具 - 根据道具显示不同的缩略图,使用相同的实例而不被破坏
所以它可能会从两个地方获取数据(自己的缩略图状态 || src 属性),我很难弄清楚如何管理它。也不太确定这是否是解决问题的正确方法。
此时我在控制台中收到无限更新循环警告。
[Vue warn]: You may have an infinite update loop in a component render function.
这是我的代码。任何帮助将不胜感激。
<template>
<div>
<label class="fileContainer">
<span class="icon is-large">
<i class="fa fa-camera"></i>
</span>
<input type="file" :index="index" @change="updateThumbnail"/>
</label>
<object
:data="pdfURL"
type="application/pdf"
:class="{visible: pdfURL != ''}">
</object>
<img :src="getSrc()" />
</div>
</template>
<script>
export default {
props: ["index", "srcProp"],
data() {
return {
imageSrc: '',
imageDataURI: '',
pdfURL: '',
}
},
methods: {
getSrc() {
if (typeof this.srcProp !== "undefined") {
this.imageSrc = ''
if (this.srcProp !== '') {
this.imageSrc = this.srcProp
} else {
this.imageSrc = this.imageDataURI
}
} else {
this.imageSrc = this.imageDataURI
}
return this.imageSrc
},
updateThumbnail(event) {
this.$emit('change')
const fileTypes = ['jpg', 'jpeg', 'png']
const imgFile = event.target.files[0] || event.srcElement.files[0]
const extension = imgFile.name.split('.').pop().toLowerCase()
const isImg = fileTypes.indexOf(extension) > -1
if (extension === 'pdf') {
const pdfURL = URL.createObjectURL(imgFile);
this.pdfURL = pdfURL
this.height = 200
return
} else if (isImg) {
var reader = new FileReader();
reader.readAsDataURL(imgFile);
reader.onload = () => {
this.imageDataURI = reader.result
return
}
} else {
alert("Please submit images or PDFs only.")
}
},
}
}
</script>
【问题讨论】:
-
似乎
getSrc应该是一个计算的,其表达式是this.srcProp || this.imageDataURI -
@RoyJ 谢谢。这似乎不起作用,因为这些图片上传者不止一个,下一个仍然有相同的
this.imageDataURI -
你的代码能做到它应该做的吗?是您唯一发出警告,还是有其他问题?
-
监听
change事件的父组件是否改变了该组件的index属性?
标签: javascript vue.js