Search code examples
cssvue.jsvuejs2css-transitionsvuejs-transition

How to custom transition for each component?


I have 3 components which I want to show a transition effect when they enter/leave.

There's 1 "main" component and the 2 others show up when you press the associated button. My current sample code is here: https://jsfiddle.net/5aq1k05L/

<transition :name="'step_' + currentView" mode="out-in">
  <component :is="currentView"></component>
</transition>

CSS:

.step_componentA-enter-active {
  transition: transform 0.4s;
}

.step_componentA-leave-active {
  transition: transform 0s;
}

.step_componentA-enter {
  transform: translateX(-100%);
}

.step_mainComponent-leave-active {
  transition: transform 0.3s;
}

.step_mainComponent-leave-to {
  transform: translateX(-100%);
}

.step_componentB-enter-active {
  transition: transform 0.4s;
}

.step_componentB-leave-active {
  transition: transform 0s;
}

.step_componentB-enter {
  transform: translateX(100%);
}

What I am trying to do:

When I click on the "componentA" button, I want that component to slide from the left while "mainComponent" is still visible in the background (not stripped out of elements like now) during the transition.

Same thing for "componentB", except it will slide from the right, and will back to the right when clicking back.

What am I missing? https://jsfiddle.net/5aq1k05L/


Solution

  • Edit 2:

    Here a working example with the componentA and componentB that are sliding over the mainComponent -> https://jsfiddle.net/5aq1k05L/8/

    I changed the transition to mode:in-out, I added a z-index for each component, and put the components in position:absolute and the app in position:relative


    Edit:

    Here a working example for your case -> https://jsfiddle.net/5aq1k05L/4/


    When you analyse the script step by step, you see that the class when the componentB is leaving is step_mainComponent-leave-active step_mainComponent-leave-to that it makes a classic toggle relative to the mainComponent style.

    If you want to use different animations, you should use enter-active-class and leave-active-class etc (see more here) - or put two vars in name, i guess, with a dynamic value relative to the previous view, in the store like currentView is.

    It could be like this :

    <transition
        :name="'step_' + currentView + '_from_' + prevView" 
        mode="out-in"
      >
    

    In the store (you ll need to update the states, mapState, etc.. as well too) :

    SET_CURRENT_VIEW(state, new_currentView) {
      state.prevView = state.currentView;
      state.currentView = new_currentView;
    }
    

    Hope it ll help you