div 的动画宽度绑定到 Vue 中的数据 属性

Animate width of div bound to data property in Vue

我有这个进度条 div,它的宽度绑定到数据 属性 结果并相应地改变。目前它还在跳,但我想为它制作动画。我想过跟踪旧值和新值并使用 css 变量将其注入 css 或仅使用 setInterval 方法,但跟踪这 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>

像这样添加 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 + '%'">

See this example

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