最近一直在学vue,今天试着又写了一遍购物车,这次将input文本框和两个增减的button做成了一个组件,相比于之前写的代码,耦合度更低,复用性更好.
因为没有写css样式,就是单纯的练习vue,所以界面不好看,见谅
从左到右依次是 商品id,商品名称,商品单价,商品数量的文本输入框,商品增减的按钮,商品数量
需求是有一个最小购买数量和最大购买数量,当加减到最大最小数量是,按钮会被禁用.文本输入框输入数量时,如果输入文字什么的会使用默认值,数值超过最大数量时会自动降为最大数量,同时增加的按钮禁用,具体的可以复制代码运行一下
html代码
<!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://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="js/index_number.js"></script>
</head>
<body>
<div id="app">
{{value}}
<table border="1px">
<tr v-for="(item, index) in showpping" :key="index">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<input-number v-model="item.currValue" :max="item.max" :min="item.min">
</input-number>
</td>
<td>{{item.currValue}}</td>
</tr>
</table>
<h1>总价 : {{toloPrice}}</h1>
</div>
<script>
let app=new Vue({
el:"#app",
data:{
value:3,
showpping:[
{id:1001,name:"戴尔电脑",price:35,min:1,max:20,currValue:1},
{id:1002,name:"联想电脑",price:26,min:1,max:10,currValue:1},
{id:1003,name:"苹果电脑",price:45,min:1,max:12,currValue:1},
{id:1004,name:"外星人电脑",price:99,min:1,max:9,currValue:1},
{id:1005,name:"骁龙电脑",price:15,min:1,max:40,currValue:1},
]
},
computed:{
toloPrice:function(){
let sum=0;
this.showpping.forEach(item => {
sum+=item.price*item.currValue;
});
return sum;
}
},
})
</script>
</body>
</html>
js
Vue.component( "inputNumber",{
template:`<div>
<input type="text" :value="currentValue" @change="handleChange">
<button @click="handleUP" :disabled="currentValue>= this.max">+</button>
<button @click="handleDown" :disabled="currentValue<= this.min">-</button>
</div>`,
props:{
max:{
type:Number
},
min:{
type:Number
},
value:{
type:Number,
default:1
}
},
data() {
return {
currentValue:this.value
}
},
watch: {
//监听属性,只要有属性发生改变都会被执行
value:function(val){
console.log(val)
this.updateValue(val)
},
currentValue(val){
this.$emit('input',val)
//每次数值改变,都会与最大值最小值进行比较,超过时禁用按钮
this.updateValue(val);
}
},
methods:{
updateValue:function(val){
if(val>this.max)val=this.max;
if(val<this.min)val=this.min;
this.currentValue=val;
},
//当文本框中的值改变时,触发
handleChange(event){
let max=this.max;
let min=this.min;
console.log(event);
//获取输入文本框中的值
let value=Number(event.target.value);
if (isValueNumber(value)) {
this.currentValue = value;
if (value>=max) {
this.currentValue= this.max;
}
if (value<=min) {
this.currentValue=this.min;
}
}else{
event.target.value=this.currentValue;
}
},
//增加时判断是否大于最大值
handleUP(){
if (this.currentValue>=this.max) return;
this.currentValue+=1;
this.$emit("input",this.currentValue)
},
//减少
handleDown(){
if (this.currentValue<=this.min) return;
this.currentValue-=1;
this.$emit("input",this.currentValue)
}
},
mounted(){
this.updateValue(this.value)
}
})
//正则表达式
function isValueNumber(value) {
return(/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value);
}