Utilizing asset URLs in style binding with Vite: A comprehensive guide

Is anyone else experiencing issues with displaying a background image from the assets folder? I am currently using an image tag and it appears properly, but when I attempt to use the background-image style, I receive a 404 error. I am utilizing Vue 3 with TypeScript and Vite 2. Any insight into what might be causing this?

Here is the code snippet that is not working:

<div style="background-image: url(./assets/img/header.png)"
></div>

However, this code works fine:

<img src="./assets/img/header.png" alt="Header" />

Answer №1

In order to resolve the URL, you will need to use the import statement within the <script> tag. It's important to note that @vue/compiler-sfc does not automatically resolve URLs in <div>.style, but it does for <img>.src, hence why the second example functions correctly.

Resolution

To expose the resolved image URL to the template, utilize the import keyword within a <script> block:

<script setup>
import imagePath from '@/assets/logo.svg'
</script>

<template>
  <div class="logo" :style="{ backgroundImage: `url(${imagePath})` }"></div>
</template>

<style>
.logo {
  height: 400px;
  width: 400px;
}
</style>

view demo

Answer №2

The reason for this issue is that vite cannot handle alias by default, so it is necessary to configure an alias in the vite config file.

There is no requirement to specify the import image in the script tag.

Simply add the following code to the vite.config.js file:

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "/src"),
      "~@": path.resolve(__dirname, "/src"),
    },
  },
});

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

Is it possible to use calc with the display property set to table-cell?

I have created a structure using divs to mimic table elements for an entry form. My goal is to make the left column, where field labels are located, 50% wide with an additional 2 em space to accommodate an asterisk marking required fields. The right column ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

Activate Vuetify to toggle a data object in an array list when the mouse hovers over

I'm currently working on a project where I need to toggle a Vuetify badge element for each item in an array when the containing div is hovered over. While I've been able to achieve a similar effect using CSS in a v-for loop with an array list, I ...

Is it possible to utilize the pre-installed "Component" component within a render function?

Can the <component> element be utilized in a render function? I encountered an error message while attempting to do so: Unknown custom element: <component> - have you properly registered the component? For recursive components, ensure that th ...

CSS: Handling Background Images Responsively

I'm experiencing an unusual issue where the image is not appearing, even though the div box shows up when I highlight elements on the page. Validation and inspection also show no issues. Here is the code: <div class="mainImage"></div> A ...

I am encountering an issue in Vue3 where the parent event handler arguments are not being typed with the child's defineEmits definition. Can anyone explain this to me

I am struggling to correctly type the parent event handler based on the child definition, but no matter what I try, I always end up with `any` as the event type. Here is a code example: <script setup lang="ts"> // Child component type Even ...

What is the best way to align my grid cells to the center?

I'm facing an issue where the grid cells do not move closer together as I resize the window, instead they just stay in their place. I want to achieve a similar layout to . To share my project code, I have uploaded it on codepen: https://codepen.io/Ale ...

Can someone please explain the distinction between $http.get() and axios.get() when used in vue.js?

I'm feeling a little bit puzzled trying to differentiate between $http.get() and axios.get(). I've searched through various sources but haven't found any answers that fully satisfy me. Can someone please offer some assistance? ...

Tips for transforming a hover menu into a clickable menu

The scenario above demonstrates that when hovering over the dropdown menu, it displays a submenu. However, I want the submenu to be displayed after clicking on the dropdown text. Could anyone provide assistance on how to change the hovermenu to a clickabl ...

Elevate column to top position in mobile display with Bootstrap

I am currently working with Bootstrap column classes and have set up four columns as follows: <div class="col-md-3"> @include('schedulizer.classes-panel') @include('schedulizer.time-span-options-panel') @include(&apos ...

Find and retrieve all data attributes with JavaScript

What is the method to retrieve all data-attributes and store them in an array? <ul data-cars="ford"> <li data-model="mustang"></li> <li data-color="blue"></li> <li data-doors="5"></li> </ul> The resultin ...

When using Lavarel, it does not support the Js Date format when sending data from Vue with axios, resulting in a 500 Internal Error being

I am encountering an issue with my Vue component's axios requests when passing dates. The input method works fine when I manually enter a date like "2021-03-06", but it fails when using a datePicker. public function store() { $attributes ...

Positioning textboxes of varying heights in a vertical alignment, causing one to commence directly below the other

Seeking assistance with creating text boxes for displaying reviews on a website. Each review is contained in a box, with varying heights based on the amount of text. Desired layout is shown in the image below, with black boxes representing review container ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

Positioning the footer to sit at the bottom of my webpage, leaving a pleasing margin at the top

One technique I frequently use to ensure my footer stays at the bottom of my page is by utilizing an empty div. Here's how the code looks: <body> <div id="canevas"> <article>My website's content</article> ...

What is the best method to adjust the width of the <option> tag within the <select> tag using CSS?

<!DOCTYPE html> <html> <head> <title>Page Title</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="s ...

What is the method to adjust the margin-left in an input checkbox?

Imagine you have: <div class="home"> <input type="checkbox"/>.... </div> I am trying to add margin-left:3px to the checkbox. This is my CSS code: .home+input[type=checkbox]{ margin-left:3px; } Can anyone assist me with this? ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

Tips for showcasing the complete image within v-parallax

For my project, I decided to go with vuetify as the frontend framework. It's a great choice! Now, I have a question about v-parallax - how can I make it display the full image without cropping? Below is some code snippet, and you can find the full cod ...

The watch function fails to trigger after the variable has been passed as parameters

When I pass the parameters from the first block of code to the second, I am unable to get the watch function to fire. Although I can retrieve the params and register them on a refresh, they are not being watched. First Block <template> <router ...