简体   繁体   English

当我更新图像但前端显示旧图像时,图像 src 会发生变化

[英]Image src changes when i update the image but frontend displays the old image

I have found weird bug in my application.我在我的应用程序中发现了奇怪的错误。 I am using VueJS3 and typescript.我正在使用 VueJS3 和打字稿。 I am creating a media gallery, where users can manage assets.我正在创建一个媒体库,用户可以在其中管理资产。 All endpoints and backend side of application works perfectly.应用程序的所有端点和后端都运行良好。 Currently i am working on updating image files(updating image field).目前我正在更新图像文件(更新图像字段)。 My code works in theory, image url updates to a new one, but even the url is newer, image that is rendered is old image(before update).我的代码理论上有效,图像 url 更新为新的,但即使 url 更新,呈现的图像也是旧图像(更新前)。 When i try to view my application in incognito window, my newer image is showing.当我尝试在隐身窗口中查看我的应用程序时,我的新图像正在显示。 But it does not work otherwise(works if and only user clears his cache) I hope i explained myself clearly, it is a little complicated :)但它不起作用(如果并且只有用户清除他的缓存)我希望我清楚地解释自己,这有点复杂:)

When i fetch the data from api, they don't have any src, so i have to create a property when using the data.当我从 api 获取数据时,它们没有任何 src,所以我必须在使用数据时创建一个属性。 Here is the code below.这是下面的代码。

const { res, err } = await this.$api.image.getAll(params)
res.data.items.forEach(async (image: Image<Populated>) => {
   image.src = this.$fileHandler(image._id)
})

Note: File handler is a special method that gives the image source by id注意:文件处理程序是一种特殊的方法,它通过 id 给出图像源

Apparently your assets get cached, and there are multiple ways to solve that.显然你的资产被缓存了,有多种方法可以解决这个问题。

Not diving too much into caching strategies and cache control tags, just do不要过多地研究缓存策略和缓存控制标签,只要做

image.src = `${this.$fileHandler(image._id)}?_=${+new Date()}`

This will generate a unique (almost) URL for your image, invalidating every previous cached one.这将为您的图像生成一个唯一的(几乎)URL,使之前缓存的每一个都无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM