下一个URL.createObjectURL不是一个函数



大家好,我正在使用next

我在服务器上以blob的形式保存了一张图片我想在客户端上显示

我的组件是这样的:

<template>
<div class="product-page">
<div class="product-image">
<img data-image="black" :src="{imgSrc}" alt class="active" />
</div>
<div class="product-info">
<h2>{{ product.name }}</h2>
<h3>{{ product.price }}</h3>
<div class="description">
<p>The purposes of bonsai are primarily contemplation for the viewer, and the pleasant exercise of effort and ingenuity for the grower.</p>
<p>By contrast with other plant cultivation practices, bonsai is not intended for production of food or for medicine. Instead, bonsai practice focuses on long-term cultivation and shaping of one or more small trees growing in a container.</p>
</div>
</div>
</div>
</template>

<script>
export default {
props: {
product: {
type: Object,
default: () => {}
}
},
computed: {
imgSrc() {
const src = URL.createObjectURL(this.product.images.data);
return src;
}
}
};
</script>

但是我一直得到以下错误:

URL。createObjectURL不是一个函数

有谁知道是什么问题吗?

此错误可能发生在服务器端,因为Node不支持URL.createObjectURL()。相反,您可以为图像创建一个数据URL,格式如下:

data:image/png;BASE64_OF_IMG_BLOB

其中BASE64_OF_IMG_BLOB

计算
  • 节点:blob.toString('base64')
  • 浏览器:
  • btoa(blob)

imgSrc看起来像这样:

export default {
computed: {
imgSrc() {
const isServer = typeof window === 'undefined'
const blob = this.product.images.data
const base64 = isServer ? blob.toString('base64') : btoa(blob)
return 'data:image/png;base64,' + base64
}
}
}

注意,:src绑定应该更新以删除花括号:

<img :src="{imgSrc}"> ❌ brackets unnecessary
<img :src="imgSrc"> ✅

最新更新