使用Vue实现IP地址的输入和焦点的自动切换
公司业务需要学习Vue,前端基础薄弱,连看好几天基础慢慢恶补上来,很多地方还需要改进,直接上代码了:
JavaScript:
1 <script> 2 Vue.directive('foces',{ 3 update:function(el,{value}){ 4 var a=el.className.substring(el.className.length-1); 5 if(a==value){ 6 el.focus(); 7 } 8 } 9 }) 10 var vm=new Vue({ 11 el:"#app", 12 data:{ 13 ip1:null, 14 focesindex:1, 15 ip2:null, 16 ip3:null, 17 ip4:null, 18 },computed:{ 19 allip:function(){ 20 return this.ip1+"."+this.ip2+"."+this.ip3+"."+this.ip4; 21 } 22 },watch:{ 23 ip1:function(newIp1){ 24 if(!this.ip1){ 25 return; 26 } 27 this.focesindex=1; 28 if(isNaN(newIp1) || newIp1>223){ 29 alert(newIp1+"不是个有效项目,请指定一个介于1和223之间的数值"); 30 this.ip1=null; 31 }else{ 32 this.ip1=newIp1; 33 if(newIp1.length==3){ 34 this.focesindex=2; 35 } 36 } 37 38 },ip2:function(newIp1){ 39 if(!this.ip2){ 40 return; 41 } 42 this.focesindex=2; 43 if(isNaN(newIp1) || newIp1>255){ 44 alert(newIp1+"不是个有效项目,请指定一个介于1和255之间的数值"); 45 this.ip2=null; 46 }else{ 47 this.ip2=newIp1; 48 if(newIp1.length==3){ 49 this.focesindex=3; 50 } 51 } 52 53 },ip3:function(newIp1){ 54 if(!this.ip3){ 55 return; 56 } 57 this.focesindex=3; 58 if(isNaN(newIp1) || newIp1>255){ 59 alert(newIp1+"不是个有效项目,请指定一个介于1和255之间的数值"); 60 this.ip3=null; 61 }else{ 62 this.ip3=newIp1; 63 if(newIp1.length==3){ 64 this.focesindex=4; 65 } 66 } 67 68 },ip4:function(newIp1){ 69 if(!this.ip4){ 70 return; 71 } 72 this.focesindex=4; 73 if(isNaN(newIp1) || newIp1>255){ 74 alert(newIp1+"不是个有效项目,请指定一个介于1和255之间的数值"); 75 this.ip4=null; 76 }else{ 77 this.ip4=newIp1; 78 } 79 80 } 81 } 82 }) 83 </script>
html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/vue.min.js" ></script> </head> <style> .input1{ border:0px;width: 50px;text-align: center; }.input2{ border:0px;width: 50px;text-align: center; }.input3{ border:0px;width: 50px;text-align: center; }.input4{ border:0px;width: 50px;text-align: center; } .active{ color:red } </style> <body> <div style="border: 2px;" id="app"> <div> <input maxlength="3" v-foces="focesindex" placeholder="1-223" class="input1" type="text" v-model="ip1"/>. <input maxlength="3" v-foces="focesindex" placeholder="0-255" class="input2" type="text" v-model="ip2"/>. <input maxlength="3" v-foces="focesindex" placeholder="0-255" class="input3" type="text" v-model="ip3"/>. <input maxlength="3" v-foces="focesindex" placeholder="0" class="input4" type="text" v-model="ip4"/>. </div> <p>{{allip}}</p> </div> </div> </body> </html>
最终结果图: