【问题标题】:async await promise vue composition api console.log is correct but not in vue templateasync await promise vue composition api console.log 正确但不在 vue 模板中
【发布时间】:2021-09-09 13:40:59
【问题描述】:

我有一个多文件输入对象“文件”,我想生成预览 blob。预览对象是正确的,但是 files.value.map 不起作用。我想将 blob 附加到“文件”对象。我错过了什么?

const files = ref([])
const previews = ref([])

const toBlob = async(file) => {
  const buffer = await file.arrayBuffer()
  const blob = new Blob([buffer])
  const srcBlob = URL.createObjectURL(blob)

  return srcBlob
}

watch(files, async() => {
  previews.value = await Promise.all(
    files.value.map((file) => toBlob(file))
  )

  await Promise.all(files.value.map(async(file) => {
     console.log(file)
     file.preview = await toBlob(file)
  }))
})

 return {
   files,
   previews
 }

这在 vue 模板中是空白的。但是,console.log 是正确的。

<span v-for="file in files" :key="file">{{file.preview}}</span>

这是正确的,显示预览 blob:

<span v-for="preview in previews" :key="preview">{{preview}}</span>

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    通过将async 函数传递给files.value.map,您将获得Promises 数组。你不能直接await这个数组,因为你只能等待一个Promise

    相反,您可以使用Promise.allPromises 的数组转换为数组的Promise

      await Promise.all(files.value.map(async(file) => {
        console.log(file)
        file.preview = await toBlob(file)
      }))
    

    【讨论】:

    • 当我实施您的更改时,file.preview 会正确显示在控制台中。但是,它并没有在 vue 模板中呈现。
    • 不确定,我对 Vue 还不太熟悉。
    【解决方案2】:

    我很确定 file.preview 的分配会破坏反应性。你可以在 Vue3 中试试这个:

    let { preview } = toRefs(file)
    preview.value = await toBlob(file)
    

    参考资料:

    【讨论】:

    【解决方案3】:

    看起来您实际上不需要将.preview 属性附加到File 对象,因为您已经将它们存储在previews[] 中,所以只需删除该代码:

    watch(files, async() => {
      previews.value = await Promise.all(
        files.value.map((file) => toBlob(file))
      )
    
      // xxx: remove
      //await Promise.all(files.value.map(async(file) => {
      //   console.log(file)
      //   file.preview = await toBlob(file)
      //}))
    })
    

    对象 URL 不会被呈现为带有字符串插值的图像(即在大括号对之间)。也就是说,{{previewObjectUrl}} 只会将 URL 呈现为字符串。

    要呈现 blob,对象 URL 必须绑定到 &lt;img&gt;.src

    <img v-for="preview in previews" :key="preview" :src="preview">
    

    demo

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-17
      • 2021-03-05
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多