Vue组件内的图片在使用Vite + Laravel时无法正常工作。

huangapple go评论65阅读模式
英文:

Images inside Vue components not working with Vite + Laravel

问题

所有图片在使用laravel和Vite之前都可以正常工作。现在在Vue组件内部使用的图片停止工作了,找不到任何解决方法。

我在laravel内有这些图片:

/resources/images/drivers/2023/

Standings.vue (resources/js/components/sections/Standings.vue):

const driverImages = import.meta.glob("/resources/images/drivers/2023/*")

例如,通过以下方式提供的图片无法找到:

http://127.0.0.1:8000/images/countries/2023/backgrounds/catalunya.jpg

但是通过laravel提供的图片可以找到,直接在blade模板中使用:

http://127.0.0.1:5173/resources/images/flag.svg

在运行npm run build后,所有图片都会出现在public/build文件夹中,但在前端页面上看不到。

英文:

All of the images worked fine before using laravel with Vite. Now images from inside Vue components stopped working and can't find any solution for this.

I have these images in laravel inside:

/resources/images/drivers/2023/

Standings.vue (resources/js/components/sections/Standings.vue)

const driverImages = import.meta.glob("/resources/images/drivers/2023/*")

For example images that are served over are not found:

http://127.0.0.1:8000/images/countries/2023/backgrounds/catalunya.jpg

But images served over laravel are found and working that are used directly in blade template:

http://127.0.0.1:5173/resources/images/flag.svg

All of the images appear in public/build folder after running npm run build but are not visible on frontend

答案1

得分: 1

我重构了当前的方法,所以不再从导入的文件夹中获取所有图像,而是现在使用以下方法来匹配文件夹内的图像:

getDriverImage(name) {
    return new URL(`/src/assets/images/drivers/2023/${name}.webp`, import.meta.url).href
},

这是唯一的方法,在运行 npm run build 后正确转换图像。这是一种不同的方法,您现在必须知道确切的图像名称以匹配资源,而不是之前使用的 import.meta.glob(),它会返回文件夹内的所有资源。

英文:

I refactored current method so instead of getting all images from imported folder, I now use method to match images inside folder like this:

 getDriverImage(name) {
            return new URL(`/src/assets/images/drivers/2023/${name}.webp`, import.meta.url).href
        },

This is the only way where images are transformed correctly after npm run build. This is now different approach, where you have to know exact image name to match the asset, vs previous import.meta.glob() where all assets inside folder were returned.

huangapple
  • 本文由 发表于 2023年6月1日 05:00:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定