之前做了一个没有连接数据库的,这次做一个有删除,增加,获取列表功能的,数据库接口连接的是本地,就不提供了。
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--//导入js包-->
<script src="js/vue.js"></script>
<!-- Bootstrap -->
<link href="./bootstrap/dist/css/bootstrap.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></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:
<!--@keyup.enter 按键也触发,还可以自定义键盘码-->
<input type="text" class="form-control" v-model="name" @keyup.enter="add">
</label>
<input type="button" value="添加" class="btn btn-primary" @click="add()">
<label>
搜索:
<!--注意:Vue中调用自定义指令的时候,都要, v-开头-->
<input type="text" class="form-control" v-model="keywords" v-focus>
</label>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>data</th>
<th>operation</th>
</tr>
</thead>
<tbody>
<!-- 之前,v-for的数据都是从data中直接取,-->
<!--现在直接定义一个方法,通过传参的形式来-->
<tr v-for="item in list " :key="item.id">
<td>{{item.id}}</td>
<td>{{item.activeCode}}</td>
<td>{{item.token}}</td>
<td>
<!-- prevent阻止默认行为-->
<a href="" @click.prevent="del(item.id)" >删除</a>
</td>
</tr>
</tbody>
</table>
</div>
<script>
//配置页面全局的访问路径,但是还不是最好方法,最好的话就引入配置方式
Vue.http.options.root='http://localhost:9091/'
//初次访问列表方法
new Vue({
el: '#app',//表示我们new的这个vue实例要控制的区域
data: {//data就是mvvm中的m
//data属性中,存放的是el中要用到的数据
name: '',
keywords:'',
list: [
]
},
created(){
this.getList()
},
methods: {
add() {
//添加品牌列表
//1.this.$http.post()中接收的三个参数
//1.1第一个:要请求的url地址
//1.2 要提交的数据,要以对象的形式提交给服务器
//1.3 第三个,是一个配置对象,要以哪种表单数据类型提交过去
//{emulateJSON:true }:pplication/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。form形式传给后台,而非json形式
//2.在post方法中使用.then 来设置成功的回调函数,如果想要拿到成功的结果,需要result.body
this.$http.post('addList',{activeCode:this.name},{ })
.then(result=>{
var result=result.body
if (result.code===0) {
//成功,手动调用getlist刷新页面
console.log("添加成功")
this.getList()
}else {
alert("添加失败")
}
})
},
getList(){ //获取所有的列表
this.$http.get('getList').then( result=>{
//注意:通过$http.get 得到的数据都是放在result.body 中
var result=result.body
if (result.code===0){
//成功
this.list=result.data.rows
}else{
alert("获取数据失败")
}
})
},
del(id){//删除品牌 ===:称为等同符,当两边值的类型相同时,直接比较值,若类型不相同,直接返回false
this.$http.get('delList'+id).then(result=>{
if(result.body.code===0){
this.getList()
}else {
alert("删除数据失败")
}
})
}
},
});
</script>
</body>
</html>