1

我有两个按钮,单击一个按钮时我需要制作元素滑动 vue 过渡效果,单击另一个按钮时我需要制作元素淡入淡出 vue 过渡效果。


<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>

我知道它不起作用,因为计算发生在模板更新之后。有没有其他方法可以解决这个问题。提前致谢。

4

1 回答 1

1

您的代码似乎是正确的。您缺少 v-if 或 v-show 来触发转换

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>

于 2021-03-12T13:08:41.903 回答