问题
Im using Nuxt.js, and have a custom component.
This component has css in the component that sets a background image using css.
I've tried the following but I get an error when I run this. The error is:
invalid expression: Invalid regular expression flags in
Component
<template>
<section class="bg-img hero is-mobile header-image" v-bind:style="{ backgroundImage: 'url(' + image + ')' }">
<div class="">
<div class="hero-body">
<div class="container">
<h1 class="title">
{{ result }}
</h1>
<h2 class="subtitle ">
Hero subtitle
</h2>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: ['result', 'image']
}
</script>
<style>
.bg-img {
background-image: url(~/assets/autumn-tree.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-color: #999;
}
</style>
回答1:
url('~@/assets/autumn-tree.jpg')
I made the same mistake thinking this was a nuxtjs problem. Webpack uses syntax to resolve assets.
~ enforces webpack to treat the request as a module request. And then @ start at root.
回答2:
I found the answer on https://github.com/nuxt/nuxt.js/issues/2123.
Basically, in the component do:
<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Content with background here</div>
回答3:
<template>
<div>
<div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
</div>
</template>
<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
data() {
return { backgroundImagePath }
}
}
</script>
回答4:
This is also another example using a combination of require and url to resolve an asset.
<b-col cols="8" class="hj_projectImage justify-content-center text-center" :style="{backgroundImage: `url(` + require(`~/assets/ProjectPictures/${this.ProjectPicture}`) + `)`}">
</b-col>
回答5:
You can write it normally but in '': 'background-image'
v-bind:style="{ 'background-image': 'url(' + api.url + ')' }"
来源:https://stackoverflow.com/questions/48436017/nuxt-js-how-to-set-css-background-image-dynamicaly