1 异步请求插件 Resource
类似于jquery中的ajax
//在项目根目录打开命令窗口安装
npm install vue-resource --save
//安装成功后 在package.json中
"dependencies": {
"vue": "^2.5.2",
"vue-resource": "^1.5.1",
"vue-router": "^3.0.1"
},
//get post请求 在package.json同级新建v-resource.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/vue-resource/dist/vue-resource.js"></script>
</head>
<body>
<div id="app">
<h1>vue-resource 插件</h1>
<a href="javascript:;" v-on:click="get">Get请求</a>
<a href="javascript:;" @click="post">Post请求</a>
<a href="javascript:;">JsonP请求</a> //跨域请求时使用
<a href="javascript:;" @click="jqAjax">仿$.ajax请求</a>
<div>
{{msg}}
</div>
</div>
<script>
new Vue({
el:"#app",
data:{
msg:'',
},
http:{ //统一访问的根目录地址
root:"http://localhost:63342/vuedemo",
},
methods:{
get(){
this.$http.get("package.json",{
params:{
userId:"101",
},
headers:{
token:"asdas",
}
}).then(res=>{
this.msg = res.data; //返回的具体的值在data中
},error=>{
this.msg = error;
});
},
post(){
this.$http.post("package.json",{
params:{
userId:"101",
},
headers:{
token:"asdas",
}
}).then(res=>{
this.msg = res.data; //返回的具体的值在data中
},error=>{
this.msg = error;
});
},
jqAjax(){
this.$http({
url:"package.json",
params:{
userId:"103"
},
headers:{
token:"aaaa"
},
timeout:5,
before:function () {
console.log("请求之前执行的函数")
}
}).then(function (res) {
this.msg = res.data; //返回的具体的值在data中
})
}
}
})
</script>
</body>
</html>
2.异步请求插件 axios
//在项目根目录打开命令窗口安装
npm install axios --save
//get post请求 在package.json同级新建axios.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/axios/dist/axios.js"></script>
</head>
<body>
<div id="app">
<h1>axios 插件</h1>
<a href="javascript:;" v-on:click="get">Get请求</a>
<a href="javascript:;" @click="post">Post请求</a>
<div>
{{msg}}
</div>
</div>
<script>
new Vue({
el:"#app",
data:{
msg:'',
},
mounted:function(){
//拦截用户所有的请求 全局拦截器
axios.interceptors.request.use(function (config) {
console.log("请求初始化的触发");
return config;
})
axios.interceptors.response.use(function (response) {
console.log("请求完成后的触发");
return response;
})
},
methods:{
get(){
axios.get("package.json",{
params:{
userId:'999'
},
headers:{
token:"tang"
}
}).then(res=>{
this.msg = res.data;
}).catch(function (error) {
console.log("erroe"+error);
})
},
post(){
axios.post("package.json",{
userId:"123"
},{
headers:{
token:"asddd"
}
}).then(res=>{
this.msg = res.data;
}).catch(function (error) {
console.log(error);
})
},
}
})
</script>
</body>
</html>