我正在使用Vue 2,并尝试将CS​​S动画包含在经常创建和销毁的元素上。以下是我的代码示例:

  export default {
    name: 'MyElement',
    methods: {
      enterStart: function (el) {
        console.log('about to enter');
        el.classList.add('testing-enter');
      },
      enter: function (el) {
        console.log('entered');
      },
      leaveStart: function (el) {
        console.log('starting to leave!');
      },
      leave: function (el) {
        console.log('leaving!');
      },
    }
  };
.testing-enter {
  animation: enter .2s;
}

.testing-leave {
  animation: leave .2s;
}

@keyframes enter {
  0% {
    opacity: 0;
    transform: scale(0);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}
@keyframes leave {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(0);
  }
}
<template>
  <div>
    <transition
      @before-enter="enterStart"
      @enter="enter"
      @leave="leaveStart"
      @leave-active="leave"
      appear
    >
      <div>My element is here!</div>
    </transition>
  </div>
</template>


首先,除非我在appear元素中包括<transition ...>,否则所有这些都无效。我知道这会使过渡发生在初始渲染中,但是我希望它们在元素创建或销毁时发生。

接下来,在我的控制台中。我可以看到enterStartenter都运行,但是即使元素被破坏,leaveStartleave也从未运行。我究竟做错了什么?

最佳答案

过渡中的元素需要一个状态(显示或隐藏)。同样,您的过渡需要一个名称,该名称必须在CSS中进行大量过渡,并且应使用



例如:

new Vue({
  el: "#app",
  data: function() {
    return {
      showThisElement: false
    }
  },
  methods: {
    toggleShow: function() {
      this.showThisElement = !this.showThisElement
    }
  }
});
    .testing-enter-active {
      animation: enter .2s;
    }

    .testing-leave-active {
      animation: leave .2s;
    }

    @keyframes enter {
      0% {
        opacity: 0;
        transform: scale(0);
      }
      100% {
        opacity: 1;
        transform: scale(1);
      }
    }
    @keyframes leave {
      0% {
        opacity: 1;
        transform: scale(1);
      }
      100% {
        opacity: 0;
        transform: scale(0);
      }
    }
   <div id="app">

  <div @click="toggleShow">Show/Hide</div>

  <transition
    name="testing">

    <div v-if="showThisElement">My element is here!</div>

  </transition>
</div>


在代码笔中,单击“显示/隐藏”以切换过渡。

http://codepen.io/anon/pen/WpZPJp

关于javascript - Vue.js动画无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42821178/

10-11 13:25