value数字 vue_基于Vue开发数字输入框组件
隨著 vue 越來越火熱, 相關組件庫也非常多啦, 只用輪子怎么夠, 還是要造起來!!!
1、概述
vue組件開發的api:props、events和slots
2、組件代碼
效果:
(1)index.html
數字輸入框組件(2)input-number.js
//驗證輸入值是否為數字
function isvaluenumber(value) {
return(/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9]*$)|(^-?0{1}$)/).test(value + '');
}
vue.component('input-number', {
//模板
template: `
-
+
`,
//props實現與父組件的通信(父組件-->子組件)
//對每個props進行校驗,props的值可以是數組,也可以是對象
props: {
max: {
//必須是數字類型
type: number,
//默認值為infinity
default: infinity
},
min: {
type: number,
default: -infinity
},
value: {
type: number,
default: 0
}
},
//vue組件為單向數據流,聲明data來引用父組件的value,在組件內部維護currentvalue
data: function() {
return {
currentvalue: this.value
}
},
//監聽:與父組件通信 (子組件-->父組件)
watch: {
currentvalue: function(val) {
//使用v-model改變value
//this指向當前組件實例
this.$emit('input', val)
}
// ,
//本示例未使用自定義函數,使用了v-mode input函數來更新value
// value: function(val) {
// //自定義事件on-change,告知父組件數字輸入框值有所改變
// this.$emit('on-change', val)
// }
},
methods: {
//父組件傳遞過來的值可能不符合條件(大于最大值,小于最小值)
updatevalue: 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 -= 1;
},
handleup: function() {
if(this.currentvalue >= this.max) {
return;
}
this.currentvalue += 1;
},
handlechange: function(event) {
var val = event.target.value.trim();
var max = this.max;
var min = this.min;
if(isvaluenumber(val)) {
val = number(val);
this.currentvalue = val;
if(val > max) {
this.current = max;
}
if(val < min) {
this.current = min;
}
} else {
//如果輸入的不是數字,將輸入的內容重置為之前的currentvalue
event.target.value = this.currentvalue;
}
}
},
//初始化
mounted: function() {
this.updatevalue(this.value);
}
})
(3)index.js
var app = new vue({
el: '#app',
data: {
//數字輸入框組件默認值為5(父組件設置初始化值)
value: 5
}
})
總結
以上所述是小編給大家介紹的基于vue開發數字輸入框組件,希望對大家有所幫助
希望與廣大網友互動??
點此進行留言吧!
總結
以上是生活随笔為你收集整理的value数字 vue_基于Vue开发数字输入框组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: birt脚本for循环语句_python
- 下一篇: c++矩阵出现奇怪的数_如何理解人们在决