Vue.js 使用 src=require() 时来自 webpack 的错误 "Cannot find module './undefined'"

Vue.js Error "Cannot find module './undefined'" from webpack when using src=require()

我正在尝试使用 img 标签中的 src="" 从本地文件夹加载图像,但我想使用后端加载它们。前端已经有了相对路径“../assets/imgs/”,后端只有名称和扩展名 ex) “1.png”。问题是它确实有效,但我收到错误消息。

这让我遇到了问题

<img width=100px height=100px :src="getIconPath(`${user.icon}`)"/>

这是被调用的函数

  methods: {
    getIconPath(iconName) {
      return iconName ? require("../assets/imgs/" + iconName) : ''
    }

这是我在控制台上收到的两条错误消息

[Vue warn]: Error in render: "Error: Cannot find module './undefined'"
found in
---> <Profile> at src/components/profile.vue
       <Navbar> at src/components/navbar.vue
         <Main> at src/main.vue
           <Root> vue.runtime.esm.js:619
Error: "Cannot find module './undefined'"
    webpackContextResolve .*$:13
    webpackContext .*$:8
    getIconPath profile.vue:74
    render profile.vue:12
    VueJS 43
    <anonymous> main.js:31
    js app.js:1415
    __webpack_require__ app.js:785
    fn app.js:151
    1 app.js:1488
    __webpack_require__ app.js:785
    checkDeferredModules app.js:46
    <anonymous> app.js:861
    <anonymous>

我发现可以提供帮助的资源很少,但他们中的许多人都说需要解决他们的问题。到目前为止,我尝试将它移动到不同的文件夹,将 require 作为函数方法移动,使用绝对路径,使用 v-attr,并在没有 require 的情况下绑定它。我仍然没有运气摆脱错误信息。这是另一个 link 遇到与我相同问题的人,但我仍然无法弄清楚他们是如何解决它的。

https://forum.vuejs.org/t/how-to-fix-the-console-log-error-when-using-require-method-to-bind-an-img-src/77979

非常感谢您的帮助!!我已经被困在这个问题上好几个小时了,我似乎找不到有用的解决方案。如果这不是从后端加载图像的好方法,请随意提出任何其他替代方法。谢谢!

我在这里猜测一下 user 是异步填充数据的。我打赌你的初始数据或商店中有这样的东西

{
  user: {}
}

这里的问题是 user.iconundefined,至少在一段时间内是这样。您在哪里不必要地将其转换为带有

的字符串
getIconPath(`${user.icon}`)

会将 undefined 转换为字符串 "undefined"(因为 JavaScript 很有趣),因此出现错误消息。简单的解决方案是使用字符串模板,即

getIconPath(user.icon)

为了避免这类问题,我会改为使用计算 属性 来解决图像导入问题。这比在每个 tick

上执行模板中的方法更有效
computed: {
  userWithIcon () {
    return {
      ...this.user, 
      icon: this.user.icon && require(`../assets/imgs/${this.user.icon}`)
    }
  }
}

并在您的模板中

<img width="100px" height="100px" :src="userWithIcon.icon">

我最近遇到了类似的问题,我通过确保在渲染视图之前准备好数据来解决这个问题。使用@Phil 假设你的数据中有类似 user: {} 的东西,你可以将整个 HTML 包装在 <div v-if="user !== null"></div> 中。这确保在尝试渲染任何图像或使用来自用户对象的任何数据之前,用户数据已准备就绪。

这应该完全消除任何错误。