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