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

Vue加载本地图片遇404错误,require()未定义的解决方法

Vue3掷骰子游戏图片加载404及require未定义问题解决方法

问题说明

在开发Vue.js掷骰子游戏时遇到两个核心问题:

  • 图片加载始终返回404错误
  • 尝试使用require()方法引入图片时,提示该方法未定义

解决思路

Vue3+Vite项目不再支持CommonJS规范的require(),需改用ES模块的资源处理方式。通过new URL('./components/icons/'+ this.img[this.dice-1], import.meta.url).href可以动态生成正确的资源路径,解决打包后资源路径不匹配导致的404问题。

修正后的完整代码

App.vue

<template>
  <div>
    <button @click="roll">roll</button>
    <p> Resultado: {{dice}} </p>
    <div v-if="dice != 0">
      <img :src="selected"/>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      img: [
        'dice1.png',
        'dice2.png',
        'dice3.png',
        'dice4.png',
        'dice5.png',
        'dice6.png',
      ],
      selected: '',
      dice: 0,
    }
  },
  created(){
    // 初始化加载第一个骰子图片
    this.selected = new URL('./components/icons/' + this.img[0], import.meta.url).href;
  },
  methods:{
    roll: function(){
      this.dice = Math.ceil(Math.random() *6);
      // 动态生成对应点数的图片路径
      this.selected = new URL('./components/icons/' + this.img[this.dice-1], import.meta.url).href;
    }
  }
}
</script>

Main.js

import { createApp } from 'vue'
import App from './App.vue'

import './assets/main.css'

createApp(App).mount('#app')

关键修正点

  1. 原代码中this.select = this.img[this.dice]存在变量名错误(应为this.selected)和数组索引越界问题(骰子点数1-6对应数组索引0-5,需减1)
  2. 移除了路径中的@别名,改用相对路径结合new URL()生成正确资源地址,适配Vite的打包规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:55:20