在样式标签中使用背景图像

我想使用我的资产文件夹中的一个组件中的 svg 图像作为背景图像。下面是我的组件的一个例子:

<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>

但是图像没有显示。路径是正确的。我的错误在哪里? 谢谢你的帮助。

73681 次浏览

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

I would recommend using style binding. I found this thread really helpful link.

Here an example using bootstrap cards

    <div
class="card-image"
:style="{ backgroundImage: 'url(' + require('@/assets/images/cards.jpg') + ')' }">

The image is in src/assets/images/cards.jpg

This is what worked for me.

<div
class="image"
v-for="(image, imageIndex) in slideshow"
:key="imageIndex"
:style="{ backgroundImage: 'url(' + require(`@/assets/${image}`) + ')', width: '300px', height: '200px' }"
></div>

Where slideshow looks like:

data() {
return {
slideshow : [
"MyImages/1.png",
"MyImages/2.png"
]
}

Make sure the image extension is lowercase. If the image has an uppercase extension, change it to be lowercase otherwise it won't work.

<style lang="scss">
.section{
background-image: url('~@/assets/photos/DSC08611.jpg'); //WORKED!
background-image: url('~@/assets/photos/DSC08611.JPG'); //DID NOT WORK
}


</style>

What worked for me was the following:

  1. Move the desired image to the public folder (myapp/public/assets/myimage.png)
  2. Build the project. This will move the assets from the public folder to the dist folder.

npm run build

  1. Now you can use your image in the component like this:
<div :style="{background: 'url(' + '\'/assets/myimage.png\'' + ') no-repeat 0 3px'}"  ></div>

If your vuejs uses file-loader, you'll take advantage of import.

<template>
<div class="container"></div>
</template>


import image from @/assets/image.svg
<script>
export default {
name: 'component'
}
</script>


<style scoped lang="scss">
.container {
height: 40px;
width: 40px;
background-image: url(image);
}
</style>