Nuxt.js: Using CSS inlined style to import images

Created on 15 Nov 2017  路  3Comments  路  Source: nuxt/nuxt.js

I have searched throughout the issues in Nuxt and Next and found no solution to importing images directly in the vue <template>.

Here is what I am trying to do:

<template lang="html">
    <div class="background" :style="{ backgroundImage: `url(${backgroundUrl})` }">
</template>

Basically this component needs to accept a prop of backgroundUrl and needs to be inline styled so that I can use this component on different pages with different backgrounds.

Thoughts?

EDIT: One way that I can think of is add the images into the static folder and call the directly, but I'm not sure that's the best way to approach this since I want all my images to be in one folder assets/images.

This question is available on Nuxt.js community (#c1883)

Most helpful comment

You may have a try.

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

<script>
import backgroundUrl from '~/assets/demo.jpg'
export default {
  data() {
    return { backgroundUrl }
  }
}
</script>

All 3 comments

You may have a try.

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

<script>
import backgroundUrl from '~/assets/demo.jpg'
export default {
  data() {
    return { backgroundUrl }
  }
}
</script>

Did some digging and realized that I have ran into a require context issue explained in https://webpack.js.org/guides/dependency-management/

I did mention that backgroundUrl is a prop. So my solution to the issue (for those interested) is:

index.vue

<app-hero :background-url="require('~/static/images/hero.jpg')">Tagline</app-hero>

AppHero.vue

<div :style="{ backgroundImage: `url(${backgroundUrl})` }">Content with background here</div>

Doing this gives me the flexibility to reuse AppHero on multiple pages with different background images. If anyone has a better solution to this let me know. I personally think including the require everywhere is dirty.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

o-alexandrov picture o-alexandrov  路  3Comments

mikekidder picture mikekidder  路  3Comments

bimohxh picture bimohxh  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments