需求:
頁面上的列表原先有3個,我們想點擊一次添加一條記錄,也可以在頭和尾刪除數據;
我們也可以刪除我們想刪除的任意一行記錄;
如果是用傳統的jquery操作,頁面中js會特別多,而且操作也很麻煩。
這里用vue.js就非常簡單。
我們先看頁面效果:

頁面初始化.png

末尾增加一項.png

刪除項.png
再來看代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>demo04</title> <link rel="stylesheet" href="../css/base/bootstrap.min.css" rel="external nofollow" > <link rel="stylesheet" href="../css/base/common.css" rel="external nofollow" ></head><body> <div class="container mt15" id="ul-lists">  <ul class="list-group" v-for="item in items">  <li class="list-group-item">   <span class="label label-default label-pill pull-right" v-on:click="removeTodo($index)">×</span>   {{item.text}} {{$index}}  </li>  </ul>  <p class="mt15">   <button type="button" class="btn btn-info" v-on:click="addAtLast($index)">在末尾增加一項</button>   <button type="button" class="btn btn-secondary" v-on:click="deleteAtTop($index)">刪除第一項</button>   <button type="button" class="btn btn-secondary" v-on:click="deleteAtBottom($index)">刪除最后一項</button>  </p> </div> <script src="../js/base/vue.js"></script>  <script src="../js/base/jquery.min.js"></script> <script src="../js/base/bootstrap.min.js"></script> <script>  new Vue({  el: '#ul-lists',  data: {   items: [   { text: 'item' },   { text: 'item' },   { text: 'item' }   ]  },  methods: {   removeTodo: function (index){   this.items.splice(index, 1)   },   addAtLast: function(index){   this.items.push({ text: 'item' })   },   deleteAtTop: function(index){    this.items.shift();   },   deleteAtBottom: function(index){    this.items.pop();   }  }  }); </script></body></html>在上面的代碼中,我們主要是通過方法來管理Items這個數據,從而實現頁面上的交互。
splice、push、shift、pop的用法和在js中一樣。
因為這里的例子都不難,就不詳細說了,大家可以照著上面的代碼試試。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答