mock.js
生成随机数据,拦截Ajax请求
1.安装 cnpm install --save-dev mock.js
2.引入mock插架到mock.js文件
3.加载mock数据到main.js require("./mock/mock")
;
模拟拦截ajax
- mock.js文件
Mock.mock("/getuser","get",()=>{
return {
data:[
{
name:"Lucy",
age:"20",
sex:"male"
},
{
name:"Linda",
age:"20",
sex:"male"
},
{
name:"Bob",
age:"20",
sex:"female"
}
]
};
});
Mock.mock("/gettable","post",{
table:[
{
school:"xy",
address:"XiAn"
},
{
school:"xy",
address:"XiAn"
},
{
school:"xy",
address:"XiAn"
}
]
});
axios
1.安装 cnpm install --save-dev axios
2.引入axios 到项目 或者组件(仅限当前组件使用)
mounted() {
Axios.get("/getuser")
.then(res => {
console.log(res.data.data);
})
.catch(error => {
console.log(error);
});
Axios.post("/gettable")
.then(res => {
console.log(res.data.table);
})
.catch(error => {
console.log(error);
});
//async 可以写多个异步等待
async function getaxios() {
try {
let user = await Axios.get("/getuser"); //regeneratorRuntime is not defined
return user;
} catch (e) {
throw e;
} finally {
}
}
getaxios()
.then(res => {
console.log(res.data.data);
})
.catch(err => {
console.log(err);
})
.finally(() => {
console.log("最终执行");
});
},
async 在vue中使用时需要将es6转换为es5,需要安装babel-plugin-transform-runtime
和babel-polyfill
,然后去babel文件配置插件名称。
vue-resource
1.cnpm install --save-dev vue-resource 安装
2.引入vue-resource
mounted() {
this.$http.get("/getuser")//get post请求方式
.then(
//请求成功
(res)=>{
console.log(res.body.data);
}
).catch(
//请求失败
(error)=>{
console.log("失败");
}
);
this.$http.post("/gettable")
.then((res)=>{
console.log(res.body.table);
})
.catch((err)=>{
console.log(err);
})
},
fetch.jsonp
处理jsonp跨域
1.cnpm install --save-dev fetch.jsonp 安装
2.引入vue-resource
mounted() {
//'fetchjsonp的使用
let src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1";
FetchJsonp(src, {
jsonpCallback: "cb", //指定回调函数的参数
jsonpCallbackFunction: "getData", //指定回调函数的函数名称
timeout: 2000 //请求超时
})
.then(res => {
console.log(res);
// {ok: true, json: ƒ}
// json: ƒ json()
// ok: true
// __proto__: Object
return res.json();
})
.then(res => {
//success
console.log(res.s);
})
.catch(error => {
console.log(error);
});
//全局引入 可以直接这样调用
//this.$fetch("")
}