Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nuxt.js - how to set css background image dynamicaly

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>
like image 488
Magick Avatar asked Jan 25 '18 05:01

Magick


4 Answers

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>
like image 146
Magick Avatar answered Nov 05 '22 10:11

Magick


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.

like image 23
Quickee Avatar answered Nov 05 '22 10:11

Quickee


<template>
  <div>
    <div class="backgroundImage" :style="{ backgroundImage: `url(${backgroundImagePath})` }">
  </div>
</template>

<script>
import backgroundImagePath from '~/assets/image.jpeg'
export default {
  data() {
    return { backgroundImagePath }
  }
}
</script>
like image 4
chandrakant sangale Avatar answered Nov 05 '22 10:11

chandrakant sangale


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>
like image 3
Hamed Jafarzadeh Avatar answered Nov 05 '22 10:11

Hamed Jafarzadeh