Incorporate an image into a Component template by utilizing a URL that is provided as a property of the Component in Vue and Vite

One of the challenges I faced was setting the 'src' attribute of an image in a Component's template from a property value. Initially, I attempted to do this as follows:

Gallery View, where the Component is called multiple times

<script setup>
import ProjectPreview from "../components/ProjectPreview.vue";
</script>

<template>
  <main>
    <ProjectPreview cover="../assets/img/projects/summary/cover.jpg" title="Summary (Illustration)"
      desc="Personal work" url="https://example.com" />
    <ProjectPreview cover="@/assets/img/projects/axes/cover.jpg" title="Axes (Concept Art)"
      desc="Prop design"
      url="https://example.com" />
    <ProjectPreview cover="@/assets/img/projects/summary/cover.jpg" title="Summary (Illustration)"
      desc="Personal work" url="https://example.com" />
    <ProjectPreview cover="@/assets/img/projects/summary/cover.jpg" title="Summary (Illustration)"
      desc="Personal work" url="https://example.com" />
  </main>
</template>

Component (ProjectPreview)

<script setup>
defineProps({
    cover: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true,
    },
    desc: {
        type: String,
        required: true,
    },
    url: {
        type: String,
        required: true,
    },
});
</script>

<template>
    <div class="card mx-1" style="width: 20rem;">
        <img :src="cover" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title text-primary">{{title}}</h5>
            <p class="card-text">{{desc}}</p>
            <a href="{{url}}" class="btn btn-danger">See full project</a>
        </div>
    </div>
</template>

Vite config

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

const path = require("path");

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      "~bootstrap": path.resolve(__dirname, "node_modules/bootstrap"),
    },
  },
});

I encountered issues with the above approach, specifically related to resolving the URL correctly (the '@' symbol wasn't resolved). Despite searching for solutions and error references in the documentation, the problem persisted. Additionally, examples illustrating loading images from a Component property were scarce.


Final code following @Yitz 's solution.

View

<script setup>
import ProjectPreview from "../components/ProjectPreview.vue";
</script>

<template>
  <main>
    <ProjectPreview cover="projects/summary/cover.jpg" title="Summary (Illustration)"
      desc="Personal work" url="https://example.com" />
    <ProjectPreview cover="projects/axes/cover.jpg" title="Axes (Concept Art)"
      desc="Prop design"
      url="https://example.com" />
  </main>
</template>

Component

<script setup>
defineProps({
    cover: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true,
    },
    desc: {
        type: String,
        required: true,
    },
    url: {
        type: String,
        required: true,
    },
});

function getUrl(file) {
    return new URL(`/src/assets/img/${file}`, import.meta.url).href;
}
</script>

<template>
    <div class="card mx-1" style="width: 20rem;">
        <img :src="getUrl(cover)" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title text-primary">{{title}}</h5>
            <p class="card-text">{{desc}}</p>
            <a href="{{url}}" class="btn btn-danger">See full project</a>
        </div>
    </div>
</template>

Answer №1

Employ

cover="projects/summary/image.jpg"

Next, implement a function

getPath(url) {
    return new URL(`/src/assets/img/${url}`, import.meta.url).href;
}

within your code.

Then utilize it as follows

<img :src="getPath(cover)" .../>

No need for the @, Vite will handle the correct path automatically.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...

Dynamic addition of CSS classes to HTML elements using PHP

I'm working on developing an application that includes multiple courses. Each course is completed over a certain number of days, such as 14 days or 20 days. To visually track progress, I've implemented a step progress bar that looks like this:htt ...

determine if the req.params parameter is void on an express route

Hi everyone, I'm a beginner with node and express and could really use some guidance. I am currently attempting to create a get request that checks if the req.params.address_line is empty, and then performs an action based on that condition. However, ...

When the submit button is clicked, only the last form within the function will be submitted

I currently have a submit button that is meant for 3 different forms. When submitting, I use the following approach: restaurantCreateForm = function(){ document.getElementById("restaurant-features" ).submit(); document.getElementById("information_ ...

What could be the reason why the toggleClass function is not being run

I've been running into a little issue with using the .toggleClass function in my code. It seems to work inconsistently, and despite reading various posts on the topic, I haven't found a solution that works for me. Could you provide some assistan ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Modify input value using jQuery upon moving to the next step

When you type into an input[text] and press the tab button, it automatically moves to the next input. If you fill out all the inputs and then want to re-fill them, the values will be highlighted in blue. However, I wanted to achieve this without having to ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Filtering Quantity Based on Specific Attribute in ReactJs

I want to implement a quantity filter that can be based on color, size, or both. For instance, when I select the red color, it should display the total quantity of red items available. However, if I choose both the color red and size small, it should show ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Building a query in Javascript by utilizing object keys and values: a step-by-step guide

I am looking to transform an object with various keys and values into a query string format, for example: obj1: { abc: "Abc", id: 1, address: "something" }. The challenge is that this object is generated dynamically, so the numbe ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

There was an issue exporting bands on Google Earth Engines in Javascript due to incompatible data types: Float32 and UInt16 were found to be inconsistent

I am attempting to export a basic AOI of a Landsat-8 image, but I keep encountering the error mentioned in the title. Can you help me understand why this error is occurring? All the bands in my image are floats so I don't see where the issue lies. var ...

javascript problem with class method for loading json file

I've encountered an issue with my class setup below. Despite most things working, the console keeps throwing an error when json.onload is triggered. The error message reads "Uncaught TypeError: Cannot read property of 'push' of undefined". ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...

use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with ...