Vue实现列表的增删改查

一.html

      <div id="app">
    <from>
      <label>id:
        <input type="text" v-model="id">
      </label>
      <label>name:
        <input type="text" v-model='name'>
      </label>
      <input type="button" value="添加" @click ="add">
      <label>
        搜索名称关键字:
        <input type="text" v-model='keywords'>
      </label>
    </from>  


    <table border="1" cellspacing='0'>

      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>CTIME</th>
          <th>OPERATION</th>
        </tr>
      </thead>
      <tbody>
        <!-- 现在自定义一个search方法,同时把所有的关键字,通过传参的形式,传递给了search方法 -->
        <!-- 在search方法内部,通过执行for循环,把所有符合搜索关键字的数据,保存到一个新数组中,返回 -->
        <tr v-for="item in search(keywords)" :key="item.id"> 
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.ctime}}</td>
          <td>
            <a href="#" @click.prevent="del(item.id)">删除</a>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

二.css

     th{
    width: 20%;
  }
  tr{
    text-align: center;
  }
  td{
    width: 20%;
  }

三.script

  let vm =new Vue({
el:"#app",
data:{
  list:[
    {id : 1, name:"奔驰",ctime:new Date()},
    {id : 2, name:"法拉利",ctime:new Date()}
  ],
  id:'',
  name:'',
  keywords:''
},
methods: {
  add(){
    let car = {id:this.id,name:this.name,ctime:new Date()}
    this.list.push(car)
    this.id=''
    this.name =''
  },
  del(id){
  //  this.list.some((item,i)=>{
  //   if(item.id ==id){
  //     this.list.splice(i,1)
  //     return true
  //   }
  //  }) 一种方法
  let index = this.list.findIndex(item =>{
    if(item.id ===id){
      return true
    }
  })
  this.list.splice(index,1)
  },
  // forEach,some,filter,findIndex都会对数组每一项,进行遍历
  search(keywords){
  //   let newList =[]
  //   this.list.forEach(item=>{
  //  if(item.name.indexOf(keywords) != -1){
  //    newList.push(item)
  //  }
  //   })
  //   return newList

   // includes('要包含的字符串'),如果包含,返回true
   let newList =this.list.filter(item=>{
     if(item.name.includes(keywords)){
       return item
     }
   })
  return newList
  },
 
  },
 })
 </script>
发布了53 篇原创文章 · 获赞 76 · 访问量 1694

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/104703876