最近學習Vue.js感覺跟不上節奏了,Vue.js用起來很方便。
主要實現功能,能添加書的內容和刪除。(用的Bootstrap的樣式)demo鏈接
標題用了自定義組件,代碼如下:
components: { 'my-title': { template: '<h1 v-text="title"></h1>', data: function () { return { title: 'Vue.js 實例練習 Bootstrap樣式' } } } }
增加書的內容和表格用的都是指令+列表渲染,vue.js構造單頁面應用確實很方便。
Vue.js提供的指令很快的渲染想要的內容。這里主要用了v-for嵌套使用。
v-for還包含2個特殊變量:$index,$key。能遍歷數組和對象。 全部代碼如下:
<!DOCTYPE html> <html"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <style> #app { width: 990px; padding: 0 15px; margin: 0 auto; } </style> <div id="app"> <my-title></my-title> <div id="divTblBook"> <table class="table table-hover"> <thead> <tr> <th v-for="b in bookShow">{{ b }}</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="item in books"> <td v-for="b in item">{{ item[$key] }} </td> <td> <button class="btn btn-primary" v-on:click="delBook(item)">刪除</button> </td> </tr> </tbody> </table> </div> <div id="divAddBook"> <p>添加書籍</p> <div v-for="b in bookShow"> <div class="form-group"> <label>{{ b }}</label> <input type="text" class="form-control" v-model="book[$key]"> </div> </div> <button class="btn btn-primary" v-on:click="addBook()">添加</button> </div> </div> <link href="http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" /> <script src="http://apps.bdimg.com/libs/vue/1.0.14/vue.js"></script> <script> var vm = new Vue({ el: "#app", components: { 'my-title': { template: '<h1 v-text="title"></h1>', data: function () { return { title: 'Vue.js 實例練習 Bootstrap樣式' } } } }, data: { books: [{ author: '曹雪芹', name: '紅樓夢', price: 32.0 }, { author: '施耐庵', name: '水滸傳', price: 30.0 }, { author: '羅貫中', name: '三國演義', price: 24.0 }, { author: '吳承恩', name: '西游記', price: 20.0 }], book: { Name: '', Author: '', price: '' }, bookShow: { Name: "書名", Author: "作者", price: "價格" } }, methods: { addBook: function () { this.books.push(this.book); this.book = ""; }, delBook: function (book) { this.books.$remove(book); } } }) </script> </body> </html>