1. 程式人生 > >Vue學習之路第十六篇:車型列表的添加與刪除項目

Vue學習之路第十六篇:車型列表的添加與刪除項目

html set clas shee char name 寶馬 list 刪除按鈕

又到了大家最喜歡的項目練習階段,學以致用,今天我們要用前幾篇的學習內容實現列表的添加與刪除。

學前準備:

①:JavaScript中的splice(index,i)方法:從已知數組的index下標開始,刪除i個元素。

②:JavaScript中的findIndex() 方法:為數組中的每個元素都調用一次函數執行。

  • 當數組中的元素在測試條件時返回 true 時, findIndex() 返回符合條件的元素的索引位置,之後的值不會再調用執行函數。
  • 如果沒有符合條件的元素返回 -1。

③:箭頭函數(=>)是在ECMAScript6 中添加的一種規範,相當於匿名函數, 簡化了函數的定義。如:x => x * x 相當於 function(x){ return x*x }

1、先來看看商品添加功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>刪除添加</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="panel panel-primary" style="margin-bottom: 0px">
            <div class="panel-heading">
                <h3 class="panel-title">車型列表項目</h3>
            </div>
            <div class="panel-body form-inline" style="text-align:center">
                 序號:
<input type="text" class="form-control" v-model="id"/> 車型:<input type="text" class="form-control" v-model="name"/> <input type="button" class="btn btn-primary" value="添加" @click="add()"/> </div> </div> <table class="table table-bordered table-hover" style="text-align: center"> <header> <tr> <td>序號</td> <td>車型</td> <td>添加時間</td> <td>操作</td> </tr> </header> <tbody> <tr v-for
="item in list" :key="item.id"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{{ item.time }}</td> <td><a href="">刪除</a></td> </tr> </tbody> </table> </div> <script type="text/javascript"> var vm = new Vue({ el : "#app", data:{ id:‘‘, name:‘‘, list:[ {id:1,name:‘奧迪‘,time:new Date()}, {id:2,name:‘寶馬‘,time:new Date()}, {id:3,name:‘奔馳‘,time:new Date()}, {id:4,name:‘保時捷‘,time:new Date()} ] }, methods:{ add(){ var car = { id:this.id, name:this.name, time:new Date() }; this.list.push(car); this.id = this.name = ‘‘; } } }) </script> </body> </html>

這裏我們定義了一個list集合,並通過在input框中輸入內容,然後把新的車型添加到list集合中並顯示在頁面上(這在上一篇v-for指令中已經舉例說明過了)。為了讓樣式更加美觀,這裏我們引入使用了Bootstrap的CSS樣式文件。

技術分享圖片

2、刪除功能頁面實現:

<td><a href="" @click.prevent="del(item.id)">刪除</a></td>

js代碼實現:

del(id){
    var index = this.list.findIndex( item => {
          if(id == item.id){
               return true;
           }
     });
    this.list.splice(index,1);
}

點擊刪除按鈕之後 ,會把當前元素的id作為參數,以此來找到該元素並刪除該元素。“刪除”操作的元素為一個a鏈接,為了防止頁面的跳轉,這裏加了事件修飾符“.prevent”來阻止頁面的跳轉。刪除函數裏用了findIndex和splice兩個函數,其作用功能在開篇已經介紹了。這個項目主要是為了整合之前用到的知識,達到鞏固的目的,實際工作中的借鑒作用還是蠻大的,算是入門級別的吧。

每天進步一點點!

Vue學習之路第十六篇:車型列表的添加與刪除項目