vue 计数器组件封装

烂漫一生 提交于 2020-03-17 12:03:15

模仿element-ui计数器封装的组件

子组件 wmmInput.vue

<template>
  <div>
    <button class="buttonStyle" @click="reduce">-</button>
    <input class="inputStyle" type="text" :disabled="inputNumberDisabled" v-model="currentValue" @click="handleChange()"/>
    <button class="buttonStyle" @click="add">+</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentValue: 0
    };
  },
  props: {
    value: {
      type: Number,
      default: 0
    },
    step: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    inputNumberDisabled() {
      return this.disabled;
    }
  },
  mounted() {
    // 更新当前值
    this.updateValue(this.value);
  },
  methods: {
    reduce() {
      this.currentValue -= this.step;
      this.$emit("change", this.currentValue);
    },
    add() {
      this.currentValue += this.step;
      this.$emit("change", this.currentValue);
    },
    handleChange(val) {
      //将自定义的change事件传给父组件
      this.$emit("change", this.currentValue);
    },
    updateValue(val) {
      this.currentValue = val;
    }
  }
};
</script>

<style scoped>
.inputStyle {
  width: 60px;
  text-align: center;
  height: 35px;
  line-height: 35px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  cursor: pointer;
}
.buttonStyle {
  width: 30px;
  height: 35px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #606266;
  background: #f5f7fa;
  cursor: pointer;
}
</style>

父组件调用 index.vue

<template>
  <div>
    <h3 style="text-align: center;">InputNumber 计数器</h3>
    <wmmInput v-model="value" :disabled="false" :step="2" @change="handleChange"></wmmInput>
  </div>
</template>

<script>
import wmmInput from "@/components/wmmInput";
export default {
  components:{
      wmmInput
  },
  data () {
    return {
     value:0
    }
  },
  methods:{
    handleChange(val) {
      console.log(val);
    },
  }
}
</script>

<style scoped>

</style>

目前只封装了step,disabled属性和change事件。
我的详细代码指路 ➡ github地址

element 计数器源码地址

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!