1. 程式人生 > >axios獲取資料 增刪改查

axios獲取資料 增刪改查

<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="./vue.js"></script>
  <!-- 1. 引入axios檔案 -->
  <script src="./axios.js"
>
</script> <style> #app{ width:600px; margin:10px auto; } .tb{ border-collapse:collapse; width: 100%; } .tb th{ background-color: #0094ff; color:white; } .tb td,.tb th
{ padding:5px; border:1px solid black; text-align: center; } .add{ padding: 5px; border:1px solid black; margin-bottom: 10px; }
</style> </head> <body> <div
id="app">
<div class="add"> 編號:<input type="text" v-model="newId" id="myIdInput" ref="idRef"> 品牌名稱:<input type="text" v-model="newName" ref="nameRef"> <input type="button" value="新增" @click="addData"> </div> <div class="add"> 品牌名稱:<input type="text" placeholder="請輸入搜尋條件" v-model="searchName" @keydown.enter="search"> </div> <div> <table class="tb"> <tr> <th>編號</th> <th>品牌名稱</th> <th>創立時間</th> <th>操作</th> </tr> <tr v-for="(item, index) in list" :key="index"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.ctime}}</td> <td> <button @click="deleteData(item.id)">刪除</button> </td> </tr> <tr v-if="list.length === 0"> <td colspan="4">沒有品牌資料</td> </tr> </table> </div> </div> </body> <script> let vm = new Vue({ el: '#app', data: { newId: '', newName: '', list: [], searchName: '' //獲取搜尋的名字 }, methods: { // 新增資料 addData() { let url = 'http://list' axios.post(url, {id: this.newId, name: this.newName, ctime: new Date()}) .then(res => { // console.log(res); if(res.status === 201) { // 重新重新整理一下列表資料 this.getList() } }) }, // 獲取列表資料方法 getList() { let url = 'http://19st' // 呼叫axios的get方法,獲取資料 axios.get(url) .then(res => { console.log(res); // 將獲取回來的資料賦值給list this.list = res.data }) .catch(err => { console.log(err); }) }, // 搜尋方法 search() { let url = 'http://1list' axios.get(url,{params: {name: this.searchName}}) .then(res => { if (res.status === 200) { this.list = res.data this.searchName = '' } }) }, // 刪除方法 deleteData(id) { let url = `http://19list/${id}` axios.delete(url) .then(res => { this.getList() }) } }, mounted () { this.getList() } }) </script> </html>