在购物类网站的开发中,当用户在将商品加入购物车时,会选择相应的购买数量,通常我们需要对购买的商品做最小和最大做相应的限止,当用户的购买数量达到系统限止时在页面中会给出相应的提示。今天绵阳动力网络公司为大家介绍用Vue实现最大值和最小值计数器的实现方法和代码。
首先我们来看最终的演示效果:
接着我们来看具体的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计数器</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style type="text/css">
#app{
text-align: center;
margin: 0 auto;
line-height: 500px;
}
#app input{
width: 50px;
height: 40px;
font-size: 20px;
border-radius: 5px;
outline: none;
/* 自定义边框 */
border: 1px solid transparent;
background-color: blue;
line-height: 30px;
color: white;
}
#app span{
padding: 20px 20px;
border: 1px;
}
</style>
</head>
<body>
<div id="app">
<input type="button" value="-" @click="sub"/>
<span>{{num}}</span>
<input type="button" value="+" @click="add"/>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
num: 1
},
methods:{
add: function(){
if(this.num<10){
this.num++;
}else{
alert("达到最大啦!");
}
},
sub: function(){
if(this.num>0){
this.num--;
}else{
alert("已经没有了!");
}
}
}
})
</script>
</body>
</html>
注意事项:
data中写需要用到的数据:num
-methods中添加两个方法:加(add)、减(sub)
使用v-text或者差值表达式将num设置给span标签
使用v-on:(简写,@)将add、sub分别绑定给+、-按钮
累加的逻辑:小于10累加,否则提示
递减的逻辑:大于0递渐,否则提示
方法中通过this关键字获取data中的数据
好了,通过以上代码就可以实现我们为大家介绍的最大值和最小值计数器的功能了,除了购物车外,你也可以应用到更多的领域去。喜欢的话记得收藏哦。