1 案例实现的目标
- 可以设置每次增加的值
- 可以设置的范围,可以设置该范围内的值为最大值
- 增加框的数不能随意设置,具有一定的范围
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
.box {
width: 60px;
height: 50px;
display: flex;
justify-content: space-around;
align-items: center;
}
.box>input {
width: 30px;
height: 30px;
}
.btn {
text-align: center;
font-size: 0;
}
.btn>button {
width: 20px;
line-height: 10px;
}
</style>
</head>
<body>
<div id="app">
<span>设置增加值:</span>
<select v-model="addnumber">
<option>1</option>
<option>3</option>
<option>5</option>
<option>10</option>
</select>
<br>
<span>设置最大值值(0~200):</span>
<input type="text" v-model.number="max" />
<count :c.number="count" :add.number="addnumber" :numax.number="max"></count>
</div>
<script type="text/javascript">
var count = {
template: `<div class="box">
<input type="text" v-model="num" />
<div class="btn">
<button type="button" @click="num>=numax?num=numax:(num+parseInt(add)>=numax?num=numax:num=num+parseInt(add))">+</button>
<button type="button" @click="num<=0?num=0:(num-add<=0?num=0:num=num-add)">-</button>
</div>
</div>`,
data() {
return {
num: this.c,
}
},
watch: {
"num": {
handler: function() {
if (this.num < 0) {
this.num = 0;
} else if (this.num >= this.numax) {
this.num = this.numax;
}
}
}
},
props: ["c", "add", "numax"],
}
new Vue({
el: "#app",
components: {
count
},
data: {
count: 1,
addnumber: 1,
max: 1
},
watch: {
"max": {
handler: function() {
if (this.max < 0) {
this.max = 0;
} else if (this.max >= 200) {
this.max = 200;
}
},
deep: true
}
}
})
</script>
</body>
</html>
vue组件实现增加
- 更新版
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
max=200,val=100,step=100,min=1
<br>
<stepper :val="100" :step="5" :max="200" :min="1" ></stepper>
</div>
<script type="text/javascript">
const stepper = {
template: `<span>
<button @click="add()" :disabled="num>=max">+</button>
<input v-model.number.lazy="num"/>
<button @click="sub()" :disabled="num<=min">-</button>
</span>`,
watch:{
"num":{
handler:function(nval,oval){
if(window.isNaN(nval)){
this.num=oval;//如果输入是文字用以前的值
}
if(nval>this.max){
this.num=this.max;
}
if(nval<this.min){
this.num=this.min;
}
}
}
},
props: {
val: {
type: Number,
default: 1
},//默认值
step: {
type: Number,
default: 1
},//步长
min: {
type: Number,
default: 1
},//最小值
max: {
type: Number,
default: 1
},//最大值
},
data() {
return {
num: null
}
},
created() {
this.num = this.val;
},
methods:{
add(){
this.num+=this.step;
if(this.num>=this.max){
this.num=this.max;
}
},
sub(){
this.num-=this.step;
if(this.num<=this.min){
this.num=this.min;
}
}
}
}
new Vue({
el: "#app",
components: {stepper}
})
</script>
</body>
</html>