How to include image in Vue Component CSS inline styles in a none relative path?

亡梦爱人 提交于 2019-12-13 04:17:57

问题


So I have this Component code

<template>
  <div class="example-class">
    <p>Test</p>
  </div>
</template>
<style>
  .example-class {
     background-image: url("HOW to include the image here?");
  }
</style>

How can I include the image in that style section code?

My component is in a directory

src/component/sample-comp/MyComponent.vue

My images are in a directory

assets/images

I already tried using @/assets/images/sample-image.png It wont include the image. It is giving an error below

 ERROR  Failed to compile with 1 errors                                                                                                                                      08:53:42
This relative module was not found:

    * ./@/assets/images/cta-bg.png in ./~/css-loader?{"minimize":false,"sourceMap":false}!./~/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-18a303e8","scoped":false,"hasInlineConfig":false}!./~/vue-loader/lib/selector.js?type=styles&index=0!./src/components/frontend/landing-layouts/CallToAction.vue

回答1:


You cannot use the @ alias as Webpack cannot understand this alias inside the <style></style> tags.

There are two options to do this.


First option:

Since @ is mapped as src/ in Webpack, using your component, your path should be background-image: url('../../assets/images/cta-bg.png') in the <style></style> tags.


Second option:

You can use the style binding directly in the <div> tag.

<div :style="backgroundImage: `url(${require(`@/assets/images/cta-bg.png`)})`">
  <p>Test</p>
</div>


来源:https://stackoverflow.com/questions/53576387/how-to-include-image-in-vue-component-css-inline-styles-in-a-none-relative-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!