Vue.js:进度上传不会在视图中呈现

时间:2017-12-05 01:01:28

标签: vue.js

我正在尝试在Vuejs + Firebase存储中制作一个上传器组件。该方法工作正常,但我无法显示在视图中上传的百分比。这是我的代码:

<template>

  <div>
    <input type="file" multiple accept="image/*" @change="detectFiles($event.target.files)">
    <div>{{progressUpload}}</div>
  </div>

</template>

<script>

import { storage } from '../firebase'
export default {
  data () {
    return {
      progressUpload: 0,
      file: File,
    }
  },
  methods: {
    detectFiles (fileList) {
      Array.from(Array(fileList.length).keys()).map( x => {
        this.upload(fileList[x])
      })
    },
    upload (file) {
      let uploadTask = storage.ref('imagenes/articulos').put(file);

      uploadTask.on('state_changed', function(snapshot) {
        this.progressUpload = Math.floor(snapshot.bytesTransferred / snapshot.totalBytes * 100);
      })

      uploadTask.then(() => {
        console.info('File uploaded!');
      })
    }
  }
}
</script>

在HTML模板中编写{{progressUpload}},不会显示任何内容。但在控制台中,结果记录完美。文件正确上传

1 个答案:

答案 0 :(得分:1)

好的,我找到了解决方案。我必须将uploadProgress计算添加到一个观察器中,该观察器返回上载任务异步方法的新值。所以,我的脚本如下:

<script>

import { storage } from '../firebase'
export default {
  data () {
    return {
      progressUpload: 0,
      file: File,
      uploadTask: ''
    }
  },
  methods: {
    detectFiles (fileList) {
      Array.from(Array(fileList.length).keys()).map( x => {
        this.upload(fileList[x])
      })
    },
    upload (file) {
      this.uploadTask = storage.ref('imagenes/articulos').put(file);

      this.uploadTask.then(() => {
        console.info('Archivo guardado correctamente');
      })
    }
  },
  watch: {
    uploadTask: function() {
      this.uploadTask.on('state_changed', sp => {
        this.progressUpload = Math.floor(sp.bytesTransferred / sp.totalBytes * 100)
      })
    }
  }
}
</script>