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