Skip to content

nuxtjs – setting background-url to image from assets doesn’t work

after lots of research I haven’t found a solution which explains why this is happening.

When trying to set the background-image in my div dynamically it doesn’t work and I am getting an 404 error. http://localhost:3000/~assets/images/postPreview.jpg 404 (Not Found)

<div
    class="post-thumbnail"
    :style="{backgroundImage: 'url(' + thumbnail + ')'}"></div>
     <div class="post-content">
          <h1> {{ title }}</h1>
          <p> {{ previewText }}</p>
      </div>
</div>

I am passing it like this (thumbnail): ~assets/images/postPreview.jpg and get the above error.

If i pass it like this then it works: _nuxt/assets/images/postPreview.jpg

I have tried this one as well but it doesn’t work.

Can anyone help me out understand what is the issue?

Answer

Your images should be placed inside static folder then use them like

:style="{backgroundImage: 'url(' + thumbnail + ')'}"></div>
thumbnail :this.$router.options.base+'images/postPreview.jpg'