无限更新循环

时间:2017-02-09 21:19:47

标签: javascript vue.js

我正在尝试在Vue.js中构建一个可重用的Image Loader组件,该组件应该:

  1. 管理自己的缩略图数据
  2. 从父母那里取src作为道具
  3. 根据道具显示不同的缩略图,使用相同的实例而不会被销毁
  4. 所以它可能需要两个地方的数据(自己的缩略图状态|| src prop),而且我很难围绕如何管理它。不太确定这是否是解决问题的正确方法。

    此时我在控制台中收到无限更新循环警告。

    [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>
    

1 个答案:

答案 0 :(得分:0)

我面临着同样的问题。让我向您解释我的了解。

使用:src="anyFunction()"时,即使获得结果,它也会重新渲染至无限时间。

在这一点上,我们得到了无限次相同的数组。尝试显示console.log('this.imgSrc'),您将获得无限数量的数组。

在这里,我们不能使用slice或splice来获取第一个数组。我还没有找到解决方案,但是我设法将变量保留在src中,而不是呈现整个函数并获取url。

<img :src="'https://maps.googleapis.com/maps/api/staticmap?zoom=15&size=500x250&markers=color:red%7Clabel:L%7C'+this.leadIpinfo.loc.split(',').slice(0,1)+','+this.Ipinfo.loc.split(',').slice(1,2) alt="loc">

在这里,我已经获取了数组,并拆分并切成2个值。

希望它可以在某些方面有所帮助。

相关问题