<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>基础组件</title> <script src="vue.js" type="text/javascript" charset="utf-8"></script> </head> <style type="text/css"> .box{ position: relative; width: 64px; height: 45px; } input{ position: absolute; left: 0; top: 0; display: inline-block; width: 45px; height: 45px; } button{ position: absolute; right: 0px; width: 20px; height: 27px; } .bt1{ position: absolute; top: 0; } .bt2{ position: absolute; bottom: -6px; } </style> <body> <div id="app"> <myp :post="1"></myp> <!-- 传入值1每次加1 --> <!-- 修改post的值改变商品添加个数 --> <p>拓展:商品添加个数内部修改</p> </div> <script type="text/javascript"> var myp = { template:` <div class='box'> <input type="text" v-model="num" @blur='tx()'/> <button @click="add()" class='bt1'>+</button> <button @click="del()" class='bt2'>-</button> </div> `, props:{ 'post':{ type:Number, default:1 } }, created(){ this.temp2 = this.post*1 console.log(this.temp2) }, data:function(){ return {num:1,temp:1,temp2:1} }, methods:{ add(){ if(this.num < 5){ this.num = this.num + this.temp2 this.temp = this.num + this.temp2 }else{ alert('最多购买5件商品') } }, del(){ if(this.num > 1){ this.num = this.num - this.temp2 this.temp = this.num - this.temp2 } }, tx(){ if(this.num > 5){ alert('最多购买5件商品') this.num = 5 this.temp = 5 }else if(typeof this.num != Number){ //判断数据类型,如果不是数字就赋值为上次输入的值 alert('请输入数字') this.num = this.temp } } } } new Vue({ el:"#app", data:{ }, components:{myp} }) </script> </body> </html>