封装axios
import axios from "axios";
const requests = axios.create({
// 基础路径
baseURL:"/mock",
// 超时时间
timeout:5000,
});
//请求拦截器
requests.interceptors.request.use((config)=>{
// config:配置对象,对象里有一个重要属性,header请求头
return config;
})
//相应拦截器
requests.interceptors.response.use((res)=>{
return res.data
},(error)=>{
return Promise.reject(new Error('failed'))
})
//对外暴露
export default requests;
编写对应接口并对外暴露
import mockRequests from './request'
// 获取bannerList的接口
export const reqGetBannerList = ()=>mockRequests.get(`/banner`);
// 注册接口
export const registerResponse = (params)=>mockRequests.post(`/register`,params)
编写返回结果
import Mock from 'mockjs'
// banner是json数据需自己新建json文件填入
import banner from './banner.json'
Mock.mock("/mock/banner",{code:200,data:banner});
Mock.mock("/mock/register",'post',function(options){
// options里有url type body
let o = JSON.parse(options.body)
if(o.username === 'xiaohua'){
return{
code:212,
message:"用户名重复"
}
}else{
return {
code:200,
message:"注册成功"
}
}
})
options {url: '/mock/register', type: 'POST', body: '{"username":"xiaohua","password":"123"}'}
注册:
点击注册按钮,在click事件中分发去注册,再action中发送异步请求,请求registerResponse接口
methods: {
postRegister(){
let username = this.userName;
let pw = this.passWord;
// console.log("name:",username,"pw:",pw)
if(username!="" && pw!=""){
this.$store.dispatch('goRegister',{
username:this.userName,password:this.passWord,
});
}
}
},
actions:{
async goRegister(context,param){
let result = await registerResponse(param);
console.log(result);
// 注册成功则跳转登录页
if(result.code == 200){
router.push({path:'/login'})
window.alert(result.message)
}else{
// 注册失败返回失败原因
alert(result.message)
}
}
},