Vue.set的使用

2018-02-09  本文已影响825人  一个废人

在工作中,我做了一个上传文件完毕时,让上传行闪一下的css样式,需要用到obj.blink让其blink样式效果在闪烁一次后消失。
HTML

<div class="uploaded-file-container" :class="{'blink':file.blink}" v-if="!file.uploading">
</div>

CSS

@-webkit-keyframes blink {
    0% {
        background-color: #eff1f6;
        opacity:1;
    }
    50% {
        background-color: #fefade;
    }
    100% {
        background-color: #eff1f6;
    }
}

.blink {
    -webkit-animation-name: blink;
    -webkit-animation-duration: 2000ms;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-timing-function: ease-in-out;
}

JS

uploadHandler(e){
      let files = e.target.files
      for(let i=0;i<files.length;i++){
        let file = files[i]
        let obj = {}
        obj.name = file.name
        obj.uploading = true
        obj.progress = 0
        this.fileStack.push(obj)
        //formData to upload
        let formData = new FormData();
        formData.append('file', file);
        let data = {}
        data.loanId = this.loanId
        data.docId = this.loanDocument.id
        data.filename = file.name
        data.file = formData
        //callback to get upload progress
        let callback = (progress)=>{
          obj.progress = progress + "%"
        }
        upload(data,callback).then((response)=>{
          setTimeout(()=>{
            obj.uploading = false
            this.validate()
                  obj.blink = true
                  setTimeout(()=>{
                    obj.blink = false
                    Vue.set(this.fileStack, this.fileStack[this.fileStack.length - 1], obj)//Due to limitations in JavaScript, Vue cannot detect the following changes to an array:When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
                  },2000)
          },1500)
        }).catch((err)=>{
          this.onError()
        })
      }
    },

我的解决方案是,在第二个setTimeout处令obj.blink = false。但是仅仅这样DOM并没有更新,blink的效果还在。于是查到VUE资料:

由于 JavaScript 的限制,Vue 不能检测以下变动的数组:
当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue
当你修改数组的长度时,例如:vm.items.length = newLength

为了解决第一类问题,以下两种方式都可以实现和 vm.items[indexOfItem] = newValue 相同的效果,同时也将触发状态更新:
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)

为了解决第二类问题,你可以使用 splice: example1.items.splice(newLength)

所以,我在第二个setTimeout按上述增加了一行Vue.set代码

setTimeout(()=>{
 obj.blink = false
 Vue.set(this.fileStack, this.fileStack[this.fileStack.length - 1], obj)
},2000)

blink变成false,DOM上的效果得以实现。
注意
最终我把
Vue.set(this.fileStack, this.fileStack[this.fileStack.length - 1], obj)
改成了
this.fileStack.splice(this.fileStack.length - 1, 1, obj)
因为第一种只能让第一行生效,目前还不知道为什么。

=========================
详见Vue官方文档:注意事项
=========================

上一篇下一篇

猜你喜欢

热点阅读