vue cli 3 – 在样式标签中使用背景图片

vue cli 3 – use background image in style tag

我想在我的一个组件中使用资产文件夹中的 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>

但是图片不显示。路径是正确的。我的错误在哪里? 感谢您的帮助。

作为 Max Martynov,在评论中突出显示,您应该使用 url('~@/assets/image.svg')

Webpack在解析assets时有一些特定的规则[1].

为了解析一个别名(@),正如你所使用的,webpack 必须将请求作为模块请求来处理。使用前缀 ~ 强制 webpack 将请求视为模块请求,类似于 require('some-module/image.svg').

参考资料

  1. https://vuejs-templates.github.io/webpack/static.html#asset-resolving-rules

我建议使用样式绑定。我发现这个帖子真的很有帮助 link

这里是一个使用 bootstrap 卡片的例子

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

图片在src/assets/images/cards.jpg

这对我有用。

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

其中 slideshow 看起来像:

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

确保图片扩展名是小写的。如果图片有大写扩展名,请将其更改为小写,否则将无法使用。

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

</style>

对我有用的是:

  1. 将所需图像移动到 public 文件夹 (myapp/public/assets/myimage.png)
  2. 构建项目。这会将资产从 public 文件夹移动到 dist 文件夹。

npm run build

  1. 现在您可以像这样在组件中使用您的图片了:
<div :style="{background: 'url(' + '\'/assets/myimage.png\'' + ') no-repeat 0 3px'}"  ></div>