Vuejs 过渡

时间:2021-06-06 05:28:59

标签: vue.js vuejs2 vue-component

我想在值发生更改但无法完成时添加转换。当值更新时,我需要更改背景。

有人可以帮我吗?

代码沙盒链接 - Vuejs Transition

<template>
  <div id="app">
    <div class="box">
      <div v-if="change > 0">
        <transition name="increase">
          <span>+ {{ amount }} </span></transition
        >
      </div>
      <div v-else-if="change < 0">
        <transition name="decrease">
          <span>- {{ amount }}</span>
        </transition>
      </div>
      <div v-else>{{ amount }}</div>
    </div>
    <br />
    <button @click="generate">Update</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      change: 2,
      amount: 100,
    };
  },
  methods: {
    generate() {
      var amounts = [100, 110, 85, 75, 190];
      let changes = [-1.2, -5, 2, 5, 1, 7];
      this.amount = amounts[Math.floor(Math.random() * amounts.length)];
      this.change = changes[Math.floor(Math.random() * changes.length)];
    },
  },
  created() {},
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.box {
  width: 100px;
  margin: 0 auto;
  border: 1px solid #ddd;
  padding: 1em 2em;
}
@keyframes higher {
  50% {
    background: rgba(50, 199, 135, 0.2);
    color: #32c787;
  }
}
@keyframes lower {
  50% {
    background: rgba(255, 86, 82, 0.2);
    color: #ff5652;
  }
}
.increase-enter {
  animation: higher 0.5s;
}
.decrease-enter {
  animation: lower 0.5s;
}
</style>

P.S - 忽略这一点,因为我的文字太短而发布。一个长期存在的事实是,读者在查看页面布局时会被页面的可读内容分散注意力。使用 Lorem Ipsum 的意义在于它或多或少地具有正态分布的字母,而不是使用“此处的内容,此处的内容”,使其看起来像可读的英语。

1 个答案:

答案 0 :(得分:1)

您可以使用 key 通知过渡元素存在差异,以便它可以再次触发动画。

此外,使用 -active 类在进入阶段应用动画。

https://codesandbox.io/s/transition-forked-vg5pu?file=/src/App.vue

<transition name="increase">
    <span :key="amount + change">+ {{ amount }}</span>
</transition>

...

.increase-enter-active {
  animation: higher 0.5s;
}