gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:14:50 25 4
gpt4 key购买 nike

我正在尝试使用 img 标签中的 src=""从本地文件夹加载图像,但我想使用后端加载它们。前端已经有相对路径,即“../assets/imgs/”,后端只有名称和扩展名,例如“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 的情况下绑定(bind)它。我仍然没有摆脱错误消息的运气。这是另一个与我有相同问题的人的链接,但我仍然无法弄清楚他们是如何解决的。

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)

为了避免这类问题,我会改为使用计算属性来解决图像导入问题。这比在模板中执行每次报价都发生的方法更有效

computed: {
userWithIcon () {
return {
...this.user,
icon: this.user.icon && require(`../assets/imgs/${this.user.icon}`)
}
}
}

并在您的模板中

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

关于javascript - 使用 src=require() 时来自 webpack 的 Vue.js 错误 "Cannot find module ' ./undefined'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61493854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com