After facing an error with the regex for adding require
to the src attribute in the json, I decided to try a different approach that ended up solving the issue.
In this scenario, I am using fetch()
to retrieve the json data from a server being monitored by json-server
. The json is structured as an array (cokeImages) of objects which can be converted using res.json()
.
{
"cokeImages": [
{
"title": "Cocacola Life",
"description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
"src": "../assets/cocacola-cans/cocacola-life.png",
"id": 1,
"name": "cocacola-life",
"nutrition": [
{ "title": "sodium", "value": "150 cl", "percent": "25%" },
{ "title": "Total Fats", "value": "0g", "percent" : "0%" },
{ "title": "sodium (mg)", "value": "40mg", "percent": "0%"},
{ "title": "potasium", "value": "4g", "percent": "0%" },
{ "title": "calcium", "value": "0g", "percent": "0%"}
]
},
{
"title": "Cocacola Zero",
"description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
"src": "../assets/cocacola-cans/cocacola-zero.png",
"id": 2,
"name": "cocacola-zero",
... (and so on)...
A crucial observation was that the name property in each object matched the name used in the images' src
. Utilizing this information, I employed the map()
method to incorporate require
into each src attribute.
mounted(){
fetch("http://localhost:3000/cokeImages")
.then(response => response.json())
.then(arrayOfOjects => {
console.log(arrayOfObjects)
this.cokeImages = data.map(eachObject => {
return {...eachObject, src: require(`../assets/cocacola-cans/${eachObject.name}.png`)}
})
console.log(this.cokeImages)
})
.catch(err => {
console.log(err.message)
})
}