Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js transition doesn't apply on page first load

I have a navbar with links that switch between two components.
I've got a fade-in animation for the switching, but it wouldn't run when you first open the page (it runs only when you use the navbar links to switch the components).
Is there any way to overcome this?

P.S. The components are just <h1>Home</h1> and <h1>About</h1>.

HTML:

<div id="app">
  <transition name="view">
      <router-view/>
  </transition>
</div>

JS (Router):

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: { name: 'home-route' }
    },
    {
      path: '/home',
      name: 'home-route',
      component: HomeComponent
    },
    {
      path: '/about',
      name: 'about-route',
      component: AboutComponent
    }
  ]
})

CSS (Animation):

.view-leave-active {
    transition: opacity 0.5s ease-in-out, transform 0.5s ease;
}

.view-enter-active {
    transition: opacity 0.5s ease-in-out, transform 0.5s ease;
    transition-delay: 0.5s;
}

.view-enter, .view-leave-to {
    opacity: 0;
}

.view-enter-to, .view-leave {
    opacity: 1;
}
like image 621
Omer Lubin Avatar asked Jan 07 '20 11:01

Omer Lubin


2 Answers

Just add "appear" attribute in the transition wrapper.
And you will need your css classes for the animtaion or transition to.
Example:

<transition name="fade" appear></transition>
like image 133
Miro Grujin Avatar answered Nov 11 '22 01:11

Miro Grujin


View transitions don't automatically work on page load as when the content is loaded they haven't been initialised yet.

You have to find another way to trigger the transition. I can think of a few options.

  1. Hide the component by default with a data prop and then in the mounted life cycle switch it to true. This should trigger the transition.
<div v-if="show"></div>
data() {
    return {
      show: false
    }
  },
  mounted() {
    this.show = true; // might need this.$nextTick
  }

  1. Use a regular css transition.

Similar to the above approach, give the parent element a class with a style

opacity: 0;
transition: opacity 0.5s ease-in-out;

Then on mount add a class to change the opacity to 1.

like image 7
T. Short Avatar answered Nov 11 '22 00:11

T. Short