首页 > 解决方案 > Vue中绑定到数据属性的div的动画宽度

问题描述

我有这个进度条 div,其宽度绑定到数据属性结果并相应更改。目前它仍在跳跃,但我想为它制作动画。我想过跟踪旧值和新值,并使用 css 变量或仅使用 setInterval 方法将其注入到 css 中,但是跟踪 2 个值似乎变得相当复杂,对我来说似乎有点矫枉过正。有没有人有更简单的想法?

<template>
      <div class="progress">
        <div class="progress-value" :style="{ 'width': result + '%' }">
          <h2>{{ result }}%</h2>
        </div>
  </div>
</template>

<script>
export default {
  props: ["result"],
};
</script>

<style scoped>
.progress {
  background: #ccc;
  border-radius: 100px;
  position: relative;
  padding: 5px 5px;
  margin: 5px 5px;
  height: 40px;
  width: auto;
}

.progress-value {
  animation: load 3s normal forwards;
  border-radius: 100px;
  background: #fff;
  height: 30px;
  text-align: center;
}

/* @keyframes load {
  0% {
width: 
  }
  100% {
    width: 
  }
} */
</style>

标签: vue.jsanimationinline-styles

解决方案


像这样添加 css 过渡:

transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 1s;

并修复绑定:

<div class="progress-value" :style="'width: ' + result + '%'">

看这个例子

<template>
  <div class="progress">
    <div class="progress-value" :style="'width: ' + result + '%'">
      <h2>{{ result }}%</h2>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      result: 5
    }
  },
  mounted() {
    this.increment()
  },
  methods: {
    increment() {
      this.result += 10
      if (this.result < 95) {
        setTimeout(this.increment, 1000)
      }
    }
  }
}
</script>
<style scoped>
.progress {
  background: #ccc;
  border-radius: 100px;
  position: relative;
  padding: 5px 5px;
  margin: 5px 5px;
  height: 40px;
  width: auto;
}

.progress-value {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 1s;
  background: #fff;
  height: 30px;
  text-align: center;
}
</style>

推荐阅读