我正在尝试使用 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 的情况下绑定它。但我仍然没有摆脱错误消息。这是其他人与我有同样问题的另一个链接,但我仍然不知道他们是如何解决的。
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.icon
is undefined
,至少在一段时间内。您不必要地将其转换为字符串的地方
getIconPath(`${user.icon}`)
将转换undefined
到字符串中"undefined"
(因为 JavaScript 很有趣),因此出现了错误消息。简单的解决方案是not使用字符串模板,即
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">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)