Dynamic Img Src Url With "or" Statement Not Working Properly In Nuxt Component
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
Solution 1:
The ||
operator doesn't catch exceptions, which is what happens when a require
d URL does not exist.
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>exportdefault {
props: {
project: Object
},
computed: {
imgUrl() {
try {
returnrequire(`@assets/${this.project?.image}`)
} catch (e) {
returnrequire('@/assets/day-1.jpg')
}
}
}
}
</script>
Solution 2:
This is how I could write it:
<template><div><img:src="require(`@/assets/${chosen}`)" /></div></template><script>exportdefault {
data() {
return {
project: {
image: 'gfs.jpg', // test this with '' (empty string)
}
}
},
computed: {
chosen() {
// optional chaining (?.) could be a nice fallback for your projectreturnthis.project?.image || 'day-1.jpg'
},
},
}
</script>
If you mistake some images or your server refreshes too quickly, you may have some weird errors in the console and fastest way would be to restart the server.
Also, more answers can be found here: Vue.js dynamic images not working
Post a Comment for "Dynamic Img Src Url With "or" Statement Not Working Properly In Nuxt Component"