首先引入vue.js再引入vue-resource,顺序不能乱,因为后者依赖于前者!
不然会出现这个情况:
先设置3个按钮:
html代码:
<div id="app">
<input type="button" value="get请求" @click="getInfo">
<input type="button" value="post请求" @click="postInfo">
<input type="button" value="jsonp请求" @click="jsonpInfo">
</div>
js代码:
<script>
var vm = new Vue({
el:'#app',
data:{
},
methods:{
getInfo(){
this.$http.get('http://vue.studyit.io/api/getlunbo').then(function(result){
// console.log(result)
// console.log(123)
})
},
postInfo(){
//手动发起的post请求,默认没有表单格式,所以有的服务器处理不了
//通过post方法的第三个参数,设置提交的内容类型为 普通表单数据格式 emulateJSON:true
this.$http.post('http://vue.studyit.io/api/post',{},{emulateJSON:true}).then(resulet=>{
console.log(result)
})
},
jsonpInfo(){
this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(resulet=>{
console.log(result)
})
}
}
})
</script>
接下来看如何听过resource请求数据渲染到列表上
首先是html代码,在此之前,引入bootstrap样式
<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="添加" class="btn btn-primary" @click="add">
</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.prevent="del(item.id)">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
JS代码:
<script src="./lib/Vue.js"></script>
<script src="./lib/vue-resource.js"></script>
<script>
//配置全局请求数据的根域名
//在每次进行http请求的时候,请求的url路径必须是相对路径
//前面不能使用/ 否则无法启用根域名的拼接
Vue.http.options.root = 'http://vue.studyit.io/'
//全局配置emulateJSON
Vue.http.options.emulateJSON = true
var vm = new Vue({
el:'#app',
data:{
id:'',
name:'',
list:[//存放所有品牌的数组
{id:1,name:'五菱宏光',ctime:new Date()},
{id:2,name:'本田',ctime:new Date()},
]
},
created(){//当实例中的data和methods初始化完毕后,实例会自动执行created生命周期函数
this.getAllList()
},
methods:{
getAllList(){//获取所有品牌列表信息
this.$http.get('api/getprodlist').then((result)=>{
//通过$HTTP获取的数据都在result.body里面
var result = result.body
if(result.status === 0){//如果成功
this.list = result.message
}else{
}
})
},
add(){//添加品牌
this.$http.post('api/addproduct',{name:this.name}).then(()=>{
var result = result.body
if(result.status === 0){
//添加成功后 再次调用列表的get方法 就能刷新最新的列表数据
this.getAllList()
}else{
alert('添加失败')
}
})
},
del(id){//删除品牌
this.$http.get('api/delproduct'+id).then(()=>{
var result = result.body
if(result.status === 0){
this.getAllList()
}else{
alert('删除失败')
}
})
}
}
})
</script>
目前还未深入学习,只能写到这边,后续会更新!欢迎在评论区留言!!!