axios改造品牌列表案例
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="lib/bootstrap.css">
<script src="lib/vue-2.6.10.js"></script>
<script src="lib/axios.min.js"></script>
</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-primary">
</div>
</div>
<table class="table table-hover table-bordered 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.prevent="del(item.id)">刪除</a>
</td>
</tr>
</tbody>
</table>
</div>
<script>
//全局的axios配置
axios.defaults.baseURL = 'http://www.liulongbin.top:3005/';
//創(chuàng)建vue實(shí)例莫秆,得到ViewMode1
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
list: [
// {id: 1, name: '五菱宏光', ctime: new Date()},
// {id: 2, name: '眾泰', ctime: new Date()},
]
},
created() { //當(dāng) vm 實(shí)例的 data 和 methods 初始化完畢后悔详,vm實(shí)例會(huì)自動(dòng)執(zhí)行這個(gè)生命周期函數(shù)
this.getAllList();
},
methods: {
add() { // 添加品牌列表到后臺(tái)服務(wù)器
//分析
//通過(guò)API借口,發(fā)送一個(gè)post請(qǐng)求
axios({
method: 'post',
url: 'api/addproduct',
data: {
name: this.name
}
}).then(res => {
// console.log(res);
var result = res.data;
if (result.status === 0) {
this.getAllList();
this.name = '';
} else {
alert('添加失敺觳怠责蝠!');
}
}).catch(error => {
console.log(error);
})
},
del(id) {//刪除品牌
axios({
method: 'get',
url: 'api/delproduct/' + id,
}).then(res => {
// console.log(res);
var data = res.data;
if (data.status === 0) {
this.getAllList();
} else {
alert('刪除失斘ァ!');
}
}).catch(error => {
console.log(error);
})
},
getAllList() { //獲取所有的品牌的列表
//分析
//由于已經(jīng)導(dǎo)入了axios這個(gè)包驳规,所以可以直接通過(guò)axios來(lái)發(fā)起數(shù)據(jù)請(qǐng)求
//根據(jù)api地址獲取數(shù)據(jù)
axios({
method: 'get',
url: 'api/getprodlist',
}).then(res => {
var data = res.data;
// console.log(data);
if (data.status === 0) { //成功
this.list = res.data.message;
} else {
alert('獲取數(shù)據(jù)失敗医男!');
}
}).catch(error => {
console.log(error);
})
}
}
});
</script>
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者