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

Vue3中如何通过CSS背景属性设置public文件夹内的图标?

Vue3中引用Public目录图片的正确方式

问题原因

Vue的public目录属于静态资源目录,其中的文件不会被Webpack编译处理,会直接原封不动复制到构建产物(dist)的根目录。你之前的错误在于:

  • 使用require()会让Webpack尝试在src目录下解析文件,而public不在Webpack的模块解析范围内
  • 使用相对路径../../../public/...同样会被Webpack当作模块路径解析,导致找不到文件

正确解决方案

1. 内联样式写法

直接使用网站根路径(以/开头)引用图片,无需require():

<template>
  <input type="text" :style="background">
</template>

<script>
export default {
  computed: {
    background() {
      return { 
        background: `url(/images/icon.png) 5px center no-repeat` 
      }
    }
  }
}
</script>

2. Scoped样式写法

同样使用根路径引用,不需要相对路径:

<template>
  <input type="text">
</template>

<style scoped>
input {
  background: url('/images/icon.png') 5px center no-repeat;
}
</style>

注意事项

  • 确保public/images/icon.png文件存在,路径拼写正确
  • 开发环境下,Vue CLI会自动将public目录的资源映射到网站根路径,直接访问http://localhost:8080/images/icon.png应该能看到图片
  • 构建生产环境后,public下的images文件夹会被复制到dist根目录,路径依然有效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 08:00:59