您可以使用 Vue 的事件处理器来实现按钮控制开始。以下是一个简单的示例:

  1. 在 Vue 组件中定义一个计数器变量和一个布尔变量来控制计数器是否开始计数。
    <template>
      <div>
        <h1>{{ count }}</h1>
        <button @click='startCounting'>Start Counting</button>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          count: 0,
          isCounting: false
        };
      },
      methods: {
        startCounting() {
          this.isCounting = true;
        }
      },
      computed: {
        countup() {
          if (this.isCounting) {
            return this.count++;
          } else {
            return this.count;
          }
        }
      }
    };
    </script>
    
  2. 在计算属性中使用 Vue CountUp 组件来实现数字的动态计数。
    <template>
      <div>
        <vue-countup-v2 :start-val='0' :end-val='countup' :duration='2' />
        <button @click='startCounting'>Start Counting</button>
      </div>
    </template>
    
    <script>
    import VueCountUpV2 from 'vue-countup-v2';
    
    export default {
      components: {
        VueCountUpV2
      },
      data() {
        return {
          count: 0,
          isCounting: false
        };
      },
      methods: {
        startCounting() {
          this.isCounting = true;
        }
      },
      computed: {
        countup() {
          if (this.isCounting) {
            return this.count++;
          } else {
            return this.count;
          }
        }
      }
    };
    </script>
    
  3. 当用户点击'开始计数'按钮时,将 isCounting 变量设置为 true,计算属性将开始计数。此时,Vue CountUp 组件将开始动态计数。
    <template>
      <div>
        <vue-countup-v2 :start-val='0' :end-val='countup' :duration='2' />
        <button @click='startCounting'>Start Counting</button>
      </div>
    </template>
    
    <script>
    import VueCountUpV2 from 'vue-countup-v2';
    
    export default {
      components: {
        VueCountUpV2
      },
      data() {
        return {
          count: 0,
          isCounting: false
        };
      },
      methods: {
        startCounting() {
          this.isCounting = true;
        }
      },
      computed: {
        countup() {
          if (this.isCounting) {
            return this.count++;
          } else {
            return this.count;
          }
        }
      }
    };
    </script>
    

原文地址: https://www.cveoy.top/t/topic/mkDJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录