Vue学习笔记1(动态新增行)
1 <template> 2 <div class="home"> 3 <h1>{{ msg }}</h1> 4 <p>Welcome to your new single-page application, built with <a href="https://vuejs.org" target="_blank">Vue.js</a>.</p> 5 <div> 6 {{20>10?aaa:bbb}} 7 </div> 8 <ul> 9 <li v-for='item in itemList' :key="item.id"> 10 {{item.name}}--{{item.sex=='0'?'男':'女'}} 11 </li> 12 </ul> 13 <input type="button" value="添加数据行" @click="AddRow()"> 14 <div v-for='(it,index) in inputList' :key="it.id"> 15 <input v-model=it.text > 16 <input type="button" value="删除" @click="delRow(it,index)"> 17 </div> 18 </div> 19 </template> 20 21 <script> 22 export default { 23 name: 'Home', 24 props: { 25 msg: String, 26 }, 27 data() { 28 return { 29 aaa: 'aaab', 30 bbb: 'bbba', 31 itemList: [ 32 { name: '张三', sex: '0', age: '15',id:'1' }, 33 { name: '李四', sex: '0', age: '22',id:'2' }, 34 { name: '王丽', sex: '1', age: '14',id:'3' }, 35 ], 36 inputList:[ 37 {id:'input1',text:'111111'}, 38 ] 39 } 40 }, 41 methods:{ 42 delRow(it,index){ 43 this.inputList.splice(index,1);//删除数组 44 }, 45 AddRow(){ 46 //添加数组,自动增加id和数字 47 var ids=[]; 48 //判断数组是否有值,有的话就取出id中的数字 49 for (let index = 0; index < this.inputList.length; index++) { 50 const element = this.inputList[index]; 51 ids.push(parseInt(element.id.replace('input',''))) 52 } 53 var maxid=0; 54 //对数组中id数字进行倒叙排序,取出最大的数字 55 if (ids.length>0) { 56 maxid=ids.sort((a,b)=>b-a)[0]; 57 } 58 maxid+=1;//最大的数组+1 59 //往数组中添加对象 60 this.inputList.push({id:'input'+maxid.toString(),text:maxid.toString()}); 61 } 62 } 63 }; 64 </script> 65 66 <!-- Add "scoped" attribute to limit CSS to this component only --> 67 <style scoped> 68 </style>