1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. <script src="./lib/vue.js"></script>
    9. </head>
    10. <body>
    11. <div id="app">
    12. <div>
    13. <label>
    14. id:<input type="text" v-model="id">
    15. </label>
    16. <label>
    17. name:<input type="text" v-model="name">
    18. </label>
    19. <label>
    20. <input type="button" value="添加" @click="add">
    21. </label>
    22. <label>
    23. <input type="text" v-model="keywords">
    24. <input type="button" value="搜索" @click="serach(keywords)">
    25. </label>
    26. </div>
    27. <table border="1" style="margin-top: 20px;">
    28. <thead>
    29. <tr>
    30. <th>id</th>
    31. <th>name</th>
    32. <th>ctime</th>
    33. <th>操作</th>
    34. </tr>
    35. </thead>
    36. <tbody>
    37. <tr v-for="(item, index) in serach(keywords)" :key="index">
    38. <td>{{item.id}}</td>
    39. <td>{{item.name}}</td>
    40. <td>{{item.ctime}}</td>
    41. <td><a href="" @click.prevent="del(item.id)">删除</a></td>
    42. </tr>
    43. </tbody>
    44. </table>
    45. </div>
    46. <script>
    47. var vm = new Vue({
    48. el: '#app',
    49. data: {
    50. id: "",
    51. name: "",
    52. keywords:"",
    53. list: [
    54. { id: 1, name: "奔驰", ctime: new Date() },
    55. { id: 2, name: "宝马", ctime: new Date() },
    56. ]
    57. },
    58. methods: {
    59. add(){
    60. var obj = { id:this.id,name:this.name,ctime:new Date()};
    61. this.list.push(obj);
    62. this.id='';
    63. this.name='';
    64. },
    65. del(id){
    66. // 根据id查找索引
    67. // 根据索引删除对应的对象
    68. // 方法二
    69. var index = this.list.findIndex(item => {
    70. if (item.id == id) {
    71. return true
    72. }
    73. })
    74. console.log(index)
    75. // this.list.splice(index, 1)
    76. // 方法一
    77. // 在数组some方法中,如果return true,就立刻终止这个数组的后续循环
    78. this.list.some((v, i) =>{
    79. if (v.id == id) {
    80. this.list.splice(i, 1)
    81. return true
    82. }
    83. })
    84. },
    85. serach(keywords) {
    86. // 第一种方法
    87. var newlist=[];
    88. this.list.forEach(item => {
    89. // item.name.indexOf(keywords) != -1 名字包含就push到新数组中去
    90. if (item.name.indexOf(keywords) != -1) {
    91. newlist.push(item)
    92. }
    93. });
    94. return newlist
    95. // 第二种方法
    96. // var newlist = this.list.filter(item=>{
    97. // if (item.name.includes(keywords)) {
    98. // return item
    99. // }
    100. // })
    101. // return newlist
    102. }
    103. }
    104. });
    105. </script>
    106. </body>
    107. </html>

    1.gif