1. 程式人生 > 程式設計 >vue2.0實現列表資料增加和刪除

vue2.0實現列表資料增加和刪除

本文例項為大家分享了vue2.0實現列表資料增加和刪除的具體程式碼,供大家參考,具體內容如下

css

<style>
  [v-cloak]{
    display: none;
  }
  table{
    width: 800px;
    border-collapse: collapse;
    margin: 20px auto;
  }
  table th,table td{
    background: #0094ff;
    color: white;
    font-size: 16px;
    padding: 5px;
    text-align: center;
    border: 1px solid black;
  }
  table td{
    background: #fff;
    color: red;
  }
</style>

html

<div id="app">
  <input type="text" v-model="id">
  <input type="text" v-model="pname">
  <button @click="addData">新增</button>
  <table>
    <tr>
      <th>編號</th>
      <th>名稱</th>
      <th>建立時間</th>
      <th>操作</th>
    </tr>
    <tr v-if="list.length == 0">
      <td colspan="4">當前列表無資料</td>
    </tr>
    <tr v-for="(item,index) in list">
      <td>{{item.id}}</td>
      <td>{{item.pname}}</td>
      <td>{{item.ctime}}</td>
      <td>
        <!-- 方法一 -->
        <!-- <a href="#" rel="external nofollow" rel="external nofollow" @click="delData(index)">刪除</a> -->
        <!-- 方法二 -->
        <a href="#" rel="external nofollow" rel="external nofollow" @click="delData(item.id)">刪除</a>
      </td>
    </tr>
  </table>
</div>

js

<script src="../dist/vue.js"></script>
<script>
  var vm = new Vue({
    el: '#app',data: {
      id: 0,pname: '',list: [
        {id: 1,pname: '賓士1',ctime: new Date}
      ]
    },methods: {
      addData(){
        // 包裝成list要求的物件
        var p = {id: this.id,pname: this.pname,ctime: new Date()}
        this.list.push(p);
        // 清空文字框中的資料
        this.id = 0;
        this.pname = '';
      },delData: function(index){
        if(!confirm('是否要刪除當前資料')){
          //當用戶點選的取消按鈕的時候,應該阻斷這個方法中的後面程式碼的繼續執行
          return;
        }

        // 方法一
        // this.list.splice(index,1);
        // 方法二:
        // 根據 id 獲取要刪除的索引,方法一是直接傳入刪除陣列的索引
        var index = this.list.findIndex(function(item){
          return item.id == index;
        });
        this.list.splice(index,1);
      }
    }
  });
</script>

效果圖

vue2.0實現列表資料增加和刪除

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。