登录
1
0
0
0
举报

VUE.js不用脚手架封装一个<input-number>组件

下面是一个示例,展示如何在 Vue 3 中使用 CDN 引入 Vue.js 并创建一个简单的数字输入框组件:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CDN Vue 3 Component</title>
  <!-- 引入 Vue.js CDN -->
  <script src="https://cdn.jsdelivr.net/npm/vue@3.2.20/dist/vue.global.min.js"></script>
</head>
<body>

<div id="app">
  <input-number v-model="quantity" :min="1" :max="10" :step="1"></input-number>
  <p>Selected quantity: {{ quantity }}</p>
</div>

<!-- 定义 InputNumber 组件模板 -->
<script>
  const app = Vue.createApp({
    data() {
      return {
        quantity: 1
      };
    }
  });

  app.component('input-number', {
    template: `
      <div>
        <button @click="decrement">-</button>
        <input type="number" :value="currentValue" @input="handleInput">
        <button @click="increment">+</button>
      </div>
    `,
    props: {
      modelValue: {
        type: Number,
        default: 0
      },
      min: {
        type: Number,
        default: -Infinity
      },
      max: {
        type: Number,
        default: Infinity
      },
      step: {
        type: Number,
        default: 1
      }
    },
    emits: ['update:modelValue'],
    data() {
      return {
        currentValue: this.modelValue
      };
    },
    watch: {
      modelValue(newVal) {
        this.currentValue = newVal;
      }
    },
    methods: {
      increment() {
        const newValue = this.currentValue + this.step;
        if (newValue <= this.max) {
          this.currentValue = newValue;
          this.$emit('update:modelValue', this.currentValue);
        }
      },
      decrement() {
        const newValue = this.currentValue - this.step;
        if (newValue >= this.min) {
          this.currentValue = newValue;
          this.$emit('update:modelValue', this.currentValue);
        }
      },
      handleInput(event) {
        let newValue = event.target.valueAsNumber;
        if (!isNaN(newValue)) {
          if (newValue > this.max) {
            newValue = this.max;
          } else if (newValue < this.min) {
            newValue = this.min;
          }
          this.currentValue = newValue;
          this.$emit('update:modelValue', this.currentValue);
        }
      }
    }
  });

  const vm = app.mount('#app');
</script>

</body>
</html>


本文内容来源于互联网,仅供参考,并不代表本网站赞同其观点和对其真实性负责。如涉及作品内容、版权和其他问题,请与本网站联系,我们将在第一时间删除内容或给予更正。
4周前更新
您的位置:教程学习
发布于:2024/07/26 13:50:05
评论0条
发布