Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue cli 3 – use background image in style tag

I want to use a svg image from my assets folder in one of my components as a background-image. Here is an example of my component:

<template>   <div class="container"></div> </template>  <script> export default {   name: 'component' } </script>  <style scoped lang="scss"> .container {   height: 40px;   width: 40px;   background-image: url('@/assets/image.svg'); } </style> 

But the image doesn't show. The Path is correct. Where is my mistake? Thanks for your help.

like image 617
iamrobin. Avatar asked Aug 12 '18 20:08

iamrobin.


People also ask

How do you change the background on Vue 3?

Adding Background Image in a Style Tag We can write: url('~@/assets/image. png'). to include an image from the assets folder as a background image.

How do I add a background image to Vue?

Adding background Image Consider we have a div element and we need to add a background image to it. In the above example, we used vue object syntax to add the image to a div element. In object syntax, CSS kebab-case properties are wrapped with single quotes.

How do I use style CSS in Vue?

Adding CSS classes in Vue We should apply the button CSS classes to the <button> in our ToDoForm component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML — by adding a class="" attribute to the element.

How do I add styles to Vue component?

In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.


1 Answers

As Max Martynov, highlighted in the comments, you should use url('~@/assets/image.svg').

 

Webpack has some specific rules when resolving assets[1].

In order to resolve an alias (@), as you are using, it is mandatory webpack handles the request as a module request. Using the prefix ~ enforces webpack to treat the request as a module request, similar to require('some-module/image.svg').

 

References

  1. https://vuejs-templates.github.io/webpack/static.html#asset-resolving-rules
like image 197
j.raymond Avatar answered Sep 19 '22 02:09

j.raymond