Unique background-image for each page in Nuxt

Viewed 344

as the title says i am trying to get a unique background-image for each page in my app. Currently i have my background-image defined in style/app.scss.

@import 'variables';
@import 'page_transition';
@import url('https://fonts.googleapis.com/css?family=Work+Sans&display=swap');
body{
  font-family: 'Open Sans', sans-serif;; // Globale font definitie
  background-image: url('../../static/background.png');
  background-repeat: no-repeat;
  background-color: $darkPurple;
  scroll-behavior: smooth;
}

So far i've tried:

Dynamicly add the background url to the wrapper in the default layout. Result: the wrapper is not the body so it was not the result i was looking for.

Added

body {
  background-image: url('../../static/background.png');
}

in the <style> for each page with scoped. Result: styling given to body is ignored. And also did the same but without scoped. Result: Each page had the same background.

During these attempts i ofcourse commented the css line that defines the background in style/app.scss

1 Answers

Inside each page, set the background attributes of the body element within the mounted() hook.

Eg.

export default {
  mounted() {
    document.body.style.backgroundColor = 'blue'
  }
}

Or for images, assuming you have an image files at /static/images/bg1.jpg.

export default {
  mounted() {
    document.body.style.backgroundImage = "url('/images/bg1.jpg')"
  }
}

Remember you're manipulating the DOM directly when the mounted() hook is called on each page. If you exclude this method on any page, the background image won't change- it'll remain the same as the page you navigated from.

Related