《vue.js实战》练习---数字输入框组件

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数字输入框</title>
</head>
<body>
<div id="app">
    <input-number v-model="value" :max="10" :min="0" :step="1"></input-number>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="input-number.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            value: 5
        }
    })
</script>
</body>
</html>

 

input-number.js:

function isValueNumber(value){
    return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+'');
}
Vue.component('input-number',{
    template: '<div class="input-number"><input type="text" :value="current" @change="inputChange" @keyup.up="reduce" @keyup.down="increase"><button @click="reduce" :disabled="current <= min">-</button><button @click="increase" :disabled="current >= max">+</button></div>',
    props: {
        value: {
            type: Number,
            default: 0
        },
        max: {
            type: Number,
            default: Infinity
        },
        min: {
            type: Number,
            default: -Infinity
        },
        step: {
            type: Number,
            default: 10
        }
    },
    data: function () {
        return {
            current: this.value
        }
    },
    methods: {
        reduce: function () {
            this.current --;
        },
        increase: function () {
            this.current +=this.step;
        },
        inputChange: function (event) {
            var val = event.target.value.trim();
            if(isValueNumber(val)){
                val = Number(val);
                this.updataValue(val);
            }else{
                event.target.value = this.currentValue;
            }
        },
        updataValue: function (val) {
            if(val >= this.max){
                val = this.max;
            }else if(val <= this.min){
                val = this.min;
            }
            this.current = val;
        }
    },
    watch: {
        current: function (val) {
            this.$emit('input',val);
        },
        value: function (val) {
            this.updataValue(val);
        }
    }
})

 

效果:

 

posted @ 2018-06-25 15:01  asimpleday  阅读(345)  评论(0编辑  收藏  举报