一、mock模拟数据
- 安装
cnpm install mockjs --save-dev
- 建立mock.js文件,并在该文件中引入mock
import Mock from "mockjs";
3.在main.js文件中引入mock.js文件
import Mock from "./mock/mock" //"./mock/mock" 为mock.js文件路径
4.在mock.js文件中使用mock方法模拟数据
mock()方法的三个参数
参数一:自定义路径
参数二:获取数据的方式 get/post
参数三:模拟的数据
以下为模拟数据的两种方法:
- 以回调函数的方法模拟数据
Mock.mock("/getuser","get",()=>{
return {
result:[
{
"id":1,
"name":"张三",
"sex":"男"
} ]
}});
- 以对象的方式模拟数据
Mock.mock("/getdata","post",{
result:[
{
"name":"张三",
"sex":"男"
}]
})
二、获取数据的三种方式
1.vue-resource请求
- 安装和配置
1.安装 cnpm install vue-resource
2.在main.js中配置
2.1 引入vue-resource
import Vueresource from 'vue-resource'; //Vueresource 为自定义变量名
2.2 给Vue使用
Vue.use(Vueresource);
- 获取数据的方法
//this.$http.get("要获取数据的路径") 或 this.$http.post("要获取数据的路径")
this.$http.get("/getuser").then(res=>{
console.log(res); //获得的数据
}).catch(error=>{
console.log(error); //请求失败返回的错误
});
2.axios请求
- 安装
cnpm install --save-dev axios
- 引入与使用:分为在单个组件使用和全局使用
以下为在单个组件中引入及其使用
//引入
import Axios from "axios";
//Axios.post("要获取数据的路径") 或Axios.get("要获取数据的路径")
Axios.post("/getdata").then(res=>{
console.log(res.data.result);
this.axiosdata=res.data.result;
}).catch(error=>{
console.log(error);
});
以下为全局引入和其使用
//在main.js中 全局引入 axios
import Axios from "axios";
//将 axios绑定到vue的全局对象上
Vue.prototype.$axios=Axios;
//在所有组件中的使用方法
this.$axios.get() / this.$axios.post()
- async函数写法
使用 await 需要相关安装和配置
1.安装 cnpm install --save-dev babel-plugin-transform-run
2.在 .babelrc 文件中配置
"plugins":["transform-runtime"]
使用 async函数获取
async function method(){
let user=await Axios.get("/getuser");
return user;
}
method().then(res=>{
console.log(res.data.result);
}).catch(error=>{
console.log(error);
});
也可直接在async函数体内捕获异常
async function method(){
try{
let user=await Axios.get("/getuser");
return user;
}
catch(e){
throw(e);
}
}
-
axios向后台数据传参问题(mock无法模拟后台接收参数)
get方式 向后台传参
//方法一 Axios.get("url"); 直接传路径
Axios.get("http://www.enheng.com/getdata?id=0299&name=enheng");
//方法二: 利用params传参
Axios.get("/getuser",{
params:{
"id":"0299",
"name":"enheng"
}
}).then(res=>{
console.log(res);
}).catch(error=>{
console.log(error);
});
post方式 向后台传参
//直接以对象的方式传参
Axios.get("/getuser",{
"id":"0299",
name:"enheng"
}).then(res=>{
console.log(res);
}).catch(error=>{
console.log(error);
});
3.fetch-jsonp请求
- 安装
cnpm install --save-dev fetch-jsonp
- 引入与使用:分为在单个组件使用和全局使用
以下为在单个组件中引入及其使用
//引入
import Fetchjsonp from "fetch-jsonp"
//使用 以百度关键字搜索接口为例
let src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1";
Fetchjsonp(src,{
jsonpCallback: "cb", //指定回调函数的参数
jsonpCallbackFunction: "getData", //指定回调函数的函数名称
timeout:2000 //请求时间
}).then(response=>{
console.log(response);
//{ok: true, json: ƒ}
return response.json();
}).then(json=>{
//请求成功返回的数据
console.log(json.s);
}).catch(ex=>{
//请求失败返回的错误
console.log(ex);
});
以下为全局引入和其使用
//在main.js中 全局引入 fetch-json
import Fetch from "fetch-jsonp";
//配置 将 axios绑定到vue的全局对象上
Vue.prototype.$fetch=Fetch;
//在所有组件中使用方法
this.$fetch("")