有朋友可以帮忙解释下这段 Vue 代码为啥要写个 setTimeout 吗?直接写在上面不行吗?

2022-03-28 15:49:17 +08:00
 coolair

代码地址如下:

https://github.com/GavinZhuLei/vue-form-making/blob/master/src/components/Upload/index.vue#L204

部分代码如下:

  xhr.onreadystatechange = () => {
    console.log(xhr)
    if (xhr.readyState === 4) {
      
      let resData = JSON.parse(xhr.response)
      if (resData && resData.url) {
        this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
          ...this.fileList[this.fileList.findIndex(item => item.key === key)],
          url: resData.url,
          percent: 100,
           status: 'success', // 这里是我加的,直接写在这里不行吗?
        })
        this.$emit('input', this.fileList)  // 这里是我加的,直接写在这里不行吗?
        // 这里为啥要 setTimeout ?
        setTimeout(() => {
          this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
            ...this.fileList[this.fileList.findIndex(item => item.key === key)],
            status: 'success'
          })
          this.$emit('input', this.fileList)
        }, 200)
      } else {
        this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
          ...this.fileList[this.fileList.findIndex(item => item.key === key)],
          status: 'error'
        })
        this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
      }
    }
  }
1271 次点击
所在节点    问与答
7 条回复
hsfzxjy
2022-03-28 16:00:28 +08:00
感觉是想让进度条在 100 停一会再显示 success
cxe2v
2022-03-28 16:06:32 +08:00
赞同一楼,可能是为了让页面有个过渡效果不至于显示突兀
nomagick
2022-03-28 16:09:13 +08:00
我的天我眼晕,读这个代码真得需要写轮眼
gadfly3173
2022-03-28 18:27:15 +08:00
这个 this.fileList 用了这么多次,可以考虑 const 成一个局部变量,好读还能提高性能。。。
wunonglin
2022-03-28 18:30:21 +08:00
这么写,但凡有个空,整个报错 😅
ruoxie
2022-03-28 18:47:43 +08:00
fileList.findIndex(item => item.key === key),这个 fileList 被轮了好多次
ruoxie
2022-03-28 18:52:49 +08:00
这个项目 4.6k Star ,我惊了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/843407

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX