1.处理跨域
有些后台没有处理跨域,我们可以直接在前端进行处理
vue.config.js
module.exports = {
devServer: {
open: true, //是否自动弹出浏览器页面
// host: "localhost",
port: '8080',
https: false,
hotOnly: false,
proxy: {
'/api': {
target: 'http://192.168.43.113:8888', //API服务器的地址(由于此处我nodejs后台用了路由,所以+了api),正常不加
ws: true, //代理websockets
changeOrigin: true, // 虚拟的站点需要更管origin
pathRewrite: { //重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
'^/api': ''
}
}
},
},
2.axiso的请求正式封装
新建 http.js文件
代码较多按需使用。注意导入的vuex,他的作用是记录请求状态(正在请求、请求成功、请求失败)
更加详细的配置文件参考
https://blog.youkuaiyun.com/wangming0123/article/details/114744135?spm=1001.2014.3001.5501
import axios from 'axios'
axios.defaults.baseURL = 'http://192.168.43.113:8888/lanlema/'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data'
// 获取 Vuex Store 实例,注意是**实例而不是 vuex 这个库
import store from '../store/index' **
/**
* 以post为例
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function post(url, params) {
return new Promise((resolve, reject) => {
//发起请求的时候开启<van-loading />
//发起请求改变vuex的loading为true
store.commit("setLoading", true);
axios.post(url, params)
.then(res => {
//模拟请求延迟
setTimeout(() => {
//返回信息之后关闭
store.commit("setLoading", false);
resolve(res.data)
}, 2000)
})
.catch(err => {
//返回信息之后关闭
store.commit("setLoading", false);
reject(err.data)
})
})
}
把页面要请求的api放在独立的文件 例如 :user.js
export const login = data => post('user/login', data)
在发送页面发送具体的请求
import { login } from "@/api/User"; // 导入我们的api接口
//登录
const apiLogin = async () => {
// 调用api接口,并且提供了两个参数
let postData = {
tel: data.tel,
pwd: data.pwd,
};
await login(postData)
.then((res) => {
//请求成功
})
.catch((error) => {
console.log(error);
});
};
3.vuex添加一个变量记录请求状态
import {
createStore
} from 'vuex'
export default createStore({
state: {
loading: false
},
mutations: {
setLoading(state,data) {
state.loading =data
},
},
actions: {},
modules: {}
})
4.在App.vue添加网络请求时的加载页面
这个组件引用vant组件库,自行安装
<template>
<div id="app">
<!-- 发起网络请求时的提示框,使用遮罩层进行展示 -->
<van-overlay :show="loading" :z-index="2">
<van-loading type="spinner" color="#1989fa" size="50px" />
</van-overlay>
<router-view />
</div>
</template>
在App.vue实时跟踪vuex的值变化
<script>
import { useStore } from "vuex";
import { reactive, toRefs, onMounted ,watch} from "vue";
export default {
setup() {
const data = reactive({
loading: false,
});
//获取vuex
let store = useStore();
//检测vuex的数据变化
watch(
() => store.state.loading,
(newValue, oldValue) => {
data.loading=newValue
}
);
return { ...toRefs(data) };
},
created() {
},
};
</script>