}
到此一个数字输入框组件基本完成,但是前面提出的后两个要求也需要实现,很简单,在input上绑定一个keydown事件,在data选项中添加数据prop_step
<input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
data() {
return{
// 保存初次父组件传递的数据
currentValue : this.value,
prop_step: 10
}
}
// 当聚焦时,按上下键改变
handleChange2(event) {
console.log(event.keyCode)
if(event.keyCode == '38') {
this.currentValue ++;
}
if(event.keyCode == '40') {
this.currentValue --;
}
}完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input-number v-model="value" :max="100" :min="0"></input-number>
</div>
</body>
</html>
<script>
function isValueNumber(value) {
return (/(^-?[0-9]+.{1}d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');
}
Vue.component('input-number',{
props: {
max: {
type: Number,
default: Infinity
},
min: {
type: Number,
default: -Infinity
},
value: {
type: Number,
default: 0
}
},
template: `
<div class="input-number">
<input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
<button @click="handleDown" :disabled="currentValue <= min">-</button>
<button @click="handleUp" :disabled="currentValue >= max">+</button>
</div>
`,
data() {
return{
// 保存初次父组件传递的数据
currentValue : this.value,
prop_step: 10
}
},
watch: {
// 监听属性currentValue与value
currentValue(val) {
// currentValue变化时,通知父组件的value也变化
this.$emit('input', val); },
value(val) {
// 父组件value改变时,子组件currentValue也改变
this.updataValue(val);
}
},
methods: {
updataValue(val) {
if(val > this.max) val = this.max;
if(val < this.min) val = this.min;
this.currentValue = val;
},
// 点击减号 减10










