Vue.js Sliding Transition For Background Images Leaves Blank Space During Transition

29 views Asked by At

I want that on each click on a nav-link in the navbar the background image should slide up or down depending if the page clicked is before or after the current page in the navbar. I want it to look like one big image sliding up or down.

With my current code, the first image slides out of the way leaving a blank white space and only after that does the new image appear.

Is there a way to apply a transition to the leaving component (in my instance the page) and one to the entering one as well, using vue.js transitions?

<template>
  <NavBar/>
  <router-view v-slot="{ Component }">
      <transition :name="transitionName()" mode="in-out">
        <component :is="Component" />
      </transition>
  </router-view>
</template>

<script>
import NavBar from './components/NavBar.vue'

export default {
  name: 'App',
  data() {
    return {
      currentRouteIndex: this.getRouteIndex(this.$route.path),
      previousRouteIndex: 0, 
    };
  },
  components: {
    NavBar
  },
  created() {
    this.preloadImages([
      require('@/assets/media/background1.webp'),
      require('@/assets/media/background2.webp'),
      require('@/assets/media/background3.webp'),
      require('@/assets/media/background4.webp'), 
      require('@/assets/media/background5.webp'),                        
    ]);
  },
  methods: {
    preloadImages(imageArray) {
      const images = [];
      for (let i = 0; i < imageArray.length; i++) {
        const img = new Image();
        img.src = imageArray[i];
        images.push(img);
      }
      this.$root.preloadedImages = images;
    },
    getRouteIndex(path) {
      const routesOrder = ['/', '/1', '/2', '/3', '/4'];
      return routesOrder.indexOf(path);
    },
    transitionName() {
      return this.currentRouteIndex > this.previousRouteIndex ? 'slide-up' : 'slide-down';
    },
  },
  watch: {
    '$route'(to, from) {
      this.previousRouteIndex = this.getRouteIndex(from.path);
      this.currentRouteIndex = this.getRouteIndex(to.path);
    }
  }, 
}
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  height: 100%;
  width: 100%;  
}

.slide-up-enter-active, .slide-up-leave-active {
  transition: transform 0.5s ease;
}
.slide-up-enter, .slide-up-leave-to {
  transform: translateY(-100%);
}

.slide-down-enter-active, .slide-down-leave-active {
  transition: transform 0.5s ease;
}
.slide-down-enter, .slide-down-leave-to {
  transform: translateY(100%);
}
</style>
0

There are 0 answers