把最近學習vue的一些知識點記錄下來,今天記錄一下Vue通過vue-resource連接數據庫接口渲染列表和添加刪除功能
首先我們得引入vue的版本文件和vue-resource.js,注意:vue-resource的引入要在vue版本文件之后
然后把列表頁面寫好,然后在methods里寫一個獲取列表數據的方法:
getAllList() { //獲取所有的品牌列表 this.$http.get('api/getprodlist').then(result => { var result = result.body if (result.status === 0) { this.list = result.message } else { alert('獲取數據失敗') } }) }
當然list是在data里面已經定義好的
data: { name: '', list: [ { id: 1, name: '五菱宏光', ctime: new Date() }, { id: 2, name: '摩托羅拉', ctime: new Date() } ] }
然后調用vue的生命周期函數里面的created()函數,調用此函數時當vm實例的data和methods初始化完畢后,vm實例會自動執行,在此函數里面調用剛剛寫的getAllList()函數。此時列表就能獲取到。添加和刪除功能類似,需要注意的是刪除的時候需要傳入對應數據的id值,我們可以在url后面直接拼接。為了方便接口地址的修改操作,可以通過全局配置,請求數據接口的根域名和全局啟用emulateJSON選項
Vue.http.options.root='http://www.liulongbin.top:3005/'; Vue.http.options.emulateJSON=true;
以下是全部代碼:
<!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>Document</title> <script src="./lib/vue-2.4.0.js"></script> <script src="./lib/vue-resource-1.3.4.js"></script> <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css"> </head> <body> <div id="app"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">添加品牌</h3> </div> <div class="panel-body form-inline"> <label> Name: <input type="text" v-model="name" class="form-control"> </label> <input type="button" value="添加" @click="add" class="btn btn-info"> </div> </div> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Ctime</th> <th>Operation</th> </tr> </thead> <tbody> <tr v-for="item in list" :key="item.id"> <td>{{ item.id}}</td> <td>{{ item.name}}</td> <td>{{ item.ctime}}</td> <td> <a href="" @click="del(item.id)">刪除</a> </td> </tr> </tbody> </table> </div> <script> // 通過全局配置,請求數據接口的根域名 Vue.http.options.root='http://www.liulongbin.top:3005/'; //全局啟用emulateJSON選項 Vue.http.options.emulateJSON=true; var vm = new Vue({ el: '#app', data: { name: '', list: [ { id: 1, name: '五菱宏光', ctime: new Date() }, { id: 2, name: '摩托羅拉', ctime: new Date() } ] }, created() { //當vm實例的data和methods初始化完畢后,vm實例會自動執行 this.getAllList() }, methods: { add() { //添加 this.$http.post('api/addproduct', { name: this.name }, { emulateJSON: true }).then(result => { if (result.body.status === 0) { //成功 this.getAllList() this.name='' } else { alert('獲取數據失敗') } }) }, getAllList() { //獲取所有的品牌列表 this.$http.get('api/getprodlist').then(result => { var result = result.body if (result.status === 0) { this.list = result.message } else { alert('獲取數據失敗') } }) }, del(id){ //刪除 this.$http.get('api/delproduct/'+id).then(result=>{ if (result.body.status === 0) { //成功 this.getAllList() } else { alert('獲取數據失敗') } }) } } }) </script> </body> </html>
使用是記得引入對應的文件。