带有“OR"的动态 img src URL语句在 NUXT 组件中无法正常工作 [英] Dynamic img src URL with "OR" statement not working properly in NUXT component
问题描述
我正在尝试根据提供给组件的 prop 动态渲染图像 src 路径,并在资产文件夹中不存在该图像时提供后备路径.这是我的图片标签:
I am trying to render an image src path dynamically based on the prop provided to the component, and provide a fallback path if that image doesn't exist in the assets folder. Here is my image tag:
<img
:src="require(`@/assets/${project.image || 'day-1.jpg'}`)"
alt="project image"
class="rounded-xl row-span-3 col-span-1"
>
对于该组件在站点上的第一个实例,{project.image}
应该(并且确实)提供来自商店的正确图像文件名:gfs.jpg
(文件树中不存在的图像)
For the first instance of this component on the site, {project.image}
should (and does) provide the proper image file name from the store: gfs.jpg
(an image that does not exist in the file tree)
在这种情况下,由于使用了 ||
或运算符,我上面的代码不应该告诉 Webpack 渲染 day-1.jpg
图像,因为未找到 gfs.jpg
中的文件?
In this case, shouldn't my code above tell Webpack to render the day-1.jpg
image, due to the ||
or operator being used, since the file at gfs.jpg
is not found?
Webpack 抛出错误 Cannot find module './gfs.jpg'
with error code 500
Webpack is throwing the error Cannot find module './gfs.jpg'
with error code 500
我还尝试使用 @error
标记从 methods: {}
调用处理程序函数,但在发生此错误时不会触发.
I also tried using an @error
tag that calls a handler function from methods: {}
, but that doesn't fire when this error occurs.
推荐答案
||
操作符不会捕获异常,这是在 require
d URL 时发生的情况不存在.
The ||
operator doesn't catch exceptions, which is what happens when a require
d URL does not exist.
实现这一目标的一种方法是使用处理 require
错误的方法或计算道具,默认为 day-1.jpg
:
One way to make that work is to use a method or a computed prop that handles the require
error, defaulting to day-1.jpg
:
<template>
<img :src="imgUrl">
</template>
<script>
export default {
props: {
project: Object
},
computed: {
imgUrl() {
try {
return require(`@assets/${this.project?.image}`)
} catch (e) {
return require('@/assets/day-1.jpg')
}
}
}
}
</script>
这篇关于带有“OR"的动态 img src URL语句在 NUXT 组件中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!