vue开发数字输入框组件

知识点

  • v-model双向绑定value

  • 父组件向子组件传递数据props

  • 解决单向数据流的问题,在子组件的data选项中声明一个currentValue,默认使用value的值

    data: function() {return {currentValue: this.value,prop_step: 10};}
    
  • watch选项监听propdata的改变

    watch: {currentValue: function (val) {this.$emit('input',val);this.$emit('on-change',val);},value:function (val) {this.updateValue = val;}}
    
  • 第一次初始化的时候对value进行过滤

    updateValue:function (val) {if(val > this.max) val = this.max;if(val < this.min) val = this.min;this.currentValue = val;}
    
  • v-on事件监听,加减数据,在子组件的methods中添加方法

    <button @click="handleDown" :disabled="currentValue <= min">-button>
    <button @click="handleUp" :disabled="currentValue >= max">+button>
    
  • 在表单中增加对键盘上下键的支持@keyup.up='handleUp' @keyup.down='handleDown'

完整代码


<html lang="en">
<head><meta charset="UTF-8"><title>数字输入框组件title>
head>
<body><div id="app">input-number>div><template id="input-number"><div class="input-number"><input @keyup.up='handleUp' @keyup.down='handleDown' type="text" :value="currentValue" @change="handleChange"  @keyup.up='handleUp' @keyup.down='handleDown'/><button @click="handleDown" :disabled="currentValue <= min">-button><button @click="handleUp" :disabled="currentValue >= max">+button>div>template><script src="../js/vue.js">script><script>Vue.component('input-number', {template: '#input-number',props: {max: {type: Number,default: Infinity},min: {type: Number,default: -Infinity},value: {type: Number,default: 0}},data: function() {return {currentValue: this.value,prop_step: 10};},watch: {currentValue: function (val) {this.$emit('input',val);this.$emit('on-change',val);},value:function (val) {this.updateValue = val;}},methods:{//过滤出正确的currentValueupdateValue:function (val) {if(val > this.max) val = this.max;if(val < this.min) val = this.min;this.currentValue = val;},handleDown:function () {if (this.currentValue <= this.min) return;this.currentValue -= this.prop_step;},handleUp:function () {if (this.currentValue >= this.max) return;this.currentValue += this.prop_step;},handleChange:function (event) {var val = event.targrt.value.trim();var max = this.max;var min = this.min;if (isValueNumber(val)){val = Number(val);this.currentValue = val;if(val > max){this.currentValue = max;}else if (val < min){this.currentValue = min;}}else {event.target.value = this.currentValue;}}},//第一次初始化时,也对value进行过滤mounted:function () {this.updateValue(this.value);}});let app = new Vue({el: '#app',data:{value: 5}});script>
body>
html>


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部