1

I have two buttons, on clicking of one button i need to make an element slide vue transition effect, on clicking of other button i need to make an element fade vue transition effect.


<template>
    <transition :name="transition ? 'slide-fade' : 'fade'">
        <p>Hello world</p>
    </transition>
    <button @click="shouldSlide">Slide</button>
    <button @click="shouldFade">Fade</button>
<template>

<script>
export default {
    data () {
        return {
            isSlide: false
        }
    },
    computed: {
        transition () {
            return this.isSlide
        }
    },
    methods: {
        shouldSlide () {
            this.isSlide = true
        },
        shouldFade () {
            this.isSlide = false
        }
    }
}
</script>

i know it won't work, because computed happens after the template update. Is there any other way to solve this. Thanks in advance.

htoniv
  • 1,658
  • 21
  • 40

1 Answers1

1

Your code seems to be correct. You are missing v-if or v-show to trigger the transition

new Vue({
  el: "#aa",
  data() {
    return {
      isSlide: false,
      show: false,
    }
  },
  computed: {
    transition() {
      return this.isSlide
    }
  },
  methods: {
    shouldSlide() {
      this.isSlide = true
      this.show = false;
      setTimeout(() => {
        this.show = true;      
      }, 0)
    },
    shouldFade() {
      this.isSlide = false
      this.show = false;
      setTimeout(() => {
        this.show = true;      
      }, 0)
    }
  }
})
.slide-leave-active,
.slide-enter-active {
  transition: 1s;
}
.slide-enter {
  transform: translate(100%, 0);
}
.slide-leave-to {
  transform: translate(-100%, 0);
}

.fade-leave-active,
.fade-enter-active {
  transition: 1s;
}
.fade-enter {
  opacity: 0;
}
.fade-leave-to {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<main id="aa">
  <transition :name="transition ? 'slide' : 'fade'">
    <p v-if="show">Hello world</p>
  </transition>
  <button @click="shouldSlide">Slide</button>
  <button @click="shouldFade">Fade</button>
<main>
Sølve T.
  • 4,159
  • 1
  • 20
  • 31
  • oh awesome, didn't know this. thanks man. – htoniv Mar 12 '21 at 13:28
  • Referring to the docs, [short answer is no](https://vuejs.org/v2/guide/transitions.html#Transitioning-Single-Elements-Components) unless it's a dynamic component or root-element. You could always just use normal css transitions via adding/removing of classes. Instead of your ternary condition on the name prop, you could add it to a dynamic class: `:class="[transition ? 'slide' : 'fade']"` – Sølve T. Mar 12 '21 at 13:32