V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
coolair
V2EX  ›  问与答

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

  •  
  •   coolair · 2022-03-28 15:49:17 +08:00 · 1260 次点击
    这是一个创建于 754 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码地址如下:

    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)
          }
        }
      }
    
    7 条回复    2022-03-28 18:52:49 +08:00
    hsfzxjy
        1
    hsfzxjy  
       2022-03-28 16:00:28 +08:00 via Android
    感觉是想让进度条在 100 停一会再显示 success
    cxe2v
        2
    cxe2v  
       2022-03-28 16:06:32 +08:00
    赞同一楼,可能是为了让页面有个过渡效果不至于显示突兀
    nomagick
        3
    nomagick  
       2022-03-28 16:09:13 +08:00
    我的天我眼晕,读这个代码真得需要写轮眼
    gadfly3173
        4
    gadfly3173  
       2022-03-28 18:27:15 +08:00
    这个 this.fileList 用了这么多次,可以考虑 const 成一个局部变量,好读还能提高性能。。。
    wunonglin
        5
    wunonglin  
       2022-03-28 18:30:21 +08:00
    这么写,但凡有个空,整个报错 😅
    ruoxie
        6
    ruoxie  
       2022-03-28 18:47:43 +08:00
    fileList.findIndex(item => item.key === key),这个 fileList 被轮了好多次
    ruoxie
        7
    ruoxie  
       2022-03-28 18:52:49 +08:00
    这个项目 4.6k Star ,我惊了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2769 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:47 · PVG 20:47 · LAX 05:47 · JFK 08:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.