Vue.js 的核心是一个响应的数据绑定系统,它让数据与 DOM 保持同步非常简单。Vue.js 拥抱数据驱动的视图概念。通俗地讲,它意味着我们在普通 HTML 模板中使用特殊的语法将 DOM “绑定”到底层数据。一旦创建了绑定,DOM 将与数据保持同步。每当修改了数据,DOM 便相应地更新。这样我们应用中的逻辑就几乎都是直接修改数据了,不必与 DOM 更新搅在一起。这让我们的代码更容易撰写、理解与维护。
html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> 7 <script src="dist/vue.min.js"></script> 8 <style type="text/css"> 9 [v-cloak] { 10 display: none; 11 } 12 </style> 13 </head> 14 <body> 15 <div class="container"> 16 <div class="col-md-6 col-md-offset-3"> 17 <h1>Vue demo</h1> 18 19 <div id="app"> 20 <table class="table table-hover "> 21 <caption></caption> 22 <thead> 23 <tr> 24 <th>序号</th> 25 <th>书名</th> 26 <th>作者</th> 27 <th>价格</th> 28 <th>操作</th> 29 </tr> 30 </thead> 31 <tbody> 32 <tr v-cloak v-for="book in books"> 33 <td>{{book.id}}</td> 34 <td>{{book.name}}</td> 35 <td>{{book.author}}</td> 36 <td>{{book.price}}</td> 37 <template v-if="book.id%2==0"> 38 <td class="text-left"> 39 <button type="button" class="btn btn-success" @click="delBook(book)">删除</button> 40 </td> 41 </template> 42 <template v-else> 43 <td class="text-left"> 44 <button type="button" class="btn btn-danger" @click="delBook(book)">删除</button> 45 </td> 46 </template> 47 </tr> 48 </tbody> 49 50 </table> 51 52 <div id="add-book"> 53 54 <legend>添加书籍</legend> 55 56 <div class="form-group"> 57 <label for="">书名</label> 58 <input type="text" class="form-control" v-model="book.name"> 59 </div> 60 61 <div class="form-group"> 62 <label for="">作者</label> 63 <input type="text" class="form-control" v-model="book.author"> 64 </div> 65 66 <div class="form-group"> 67 <label for="">价格</label> 68 <input type="text" class="form-control" v-model="book.price"> 69 </div> 70 71 <button class="btn btn-primary btn-block" v-on:click="addBook()">添加</button> 72 </div> 73 74 </div> 75 76 </div> 77 </div> 78 <script type="text/javascript" src="1.js"></script> 79 </body> 80 </html>
js
new Vue({ el: '#app', methods: { addBook: function() { //计算书的id this.book.id = this.books.length + 1; this.books.push(this.book); //将input中的数据重置 this.book = {}; }, delBook: function(book) { var blength = this.books.length; this.books.splice(book.id-1, 1); for( var i = 0; i < blength ; i++) { if(book.id < this.books[i].id) { this.books[i].id -= 1; } } } }, data: { book: { id: 0, author: '', name: '', price: '' }, books: [{ id: 1, author: '曹雪芹', name: '红楼梦', price: 32.0 }, { id: 2, author: '施耐庵', name: '水浒传', price: 30.0 }, { id: '3', author: '罗贯中', name: '三国演义', price: 24.0 }, { id: 4, author: '吴承恩', name: '西游记', price: 20.0 }] } });