You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+Vite环境下Vue组件内图片无法加载问题求助

Laravel + Vite 环境下Vue组件内图片无法加载的解决方案

问题核心

切换到Laravel+Vite组合后,Vue组件内引用的图片无法加载——尽管执行npm run build后图片已生成在public/build目录,但前端仍无法正常访问;而Blade模板中直接访问开发服务器端口的图片能正常显示,这是因为Vite的资源解析规则和传统工具存在差异。

解决步骤

1. 修正资源引用路径

Vite不支持直接用绝对路径指向/resources目录,需要改为相对当前组件的路径。
你的Standings.vue位于resources/js/components/sections/,所以要回退到resources目录后再指向图片文件夹:

// 替换原有的glob路径
const driverImages = import.meta.glob("../../../../images/drivers/2023/*")

2. 正确获取图片URL

通过import.meta.glob获取的是模块引用,需要异步加载才能拿到正确的资源URL:

<template>
  <img :src="getDriverImage('hamilton.jpg')" alt="Driver Portrait" />
</template>

<script setup>
// 用相对路径匹配图片文件
const driverImages = import.meta.glob("../../../../images/drivers/2023/*")

async function getDriverImage(filename) {
  const imagePath = `../../../../images/drivers/2023/${filename}`
  // 检查该图片是否在匹配列表中
  if (driverImages[imagePath]) {
    const imageModule = await driverImages[imagePath]()
    return imageModule.default
  }
  return '' // 图片不存在时返回空
}
</script>

3. 配置资源别名(可选优化)

如果不想写冗长的相对路径,可以在vite.config.js中配置别名,简化引用:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
  plugins: [
    laravel({
      input: ['resources/css/app.css', 'resources/js/app.js'],
      refresh: true,
    }),
  ],
  resolve: {
    alias: {
      '@images': '/resources/images', // 定义图片目录别名
    },
  },
});

之后在Vue组件中就可以用别名引用:

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

4. 确保Build后资源正确加载

执行npm run build后,所有资源会打包到public/build,此时必须通过Laravel的@vite指令引入资源,不能直接访问开发服务器端口:

{{-- 在Blade模板头部添加 --}}
@vite(['resources/css/app.css', 'resources/js/app.js'])

这样页面会自动加载build后的静态资源,包括处理后的图片文件。

内容的提问来源于stack exchange,提问作者Slasher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 23:55:10