Vue3 table表格使用axios调用后端Api数据,统一返回格式
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
1.安装axios
npm install axios
2.封装axios
import axios, {
AxiosRequestConfig,
AxiosRequestHeaders,
AxiosResponse,
} from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { storeToRefs } from "pinia";
import appStore from "@/store/appStore";
let { token } = storeToRefs(appStore());
const state = {
ok: 0,//请求成功状态码
};
//返回数据规则
interface IResponseData<T> {
status: number;
message?: string;
data: T;
code: string;
}
//请求默认配置规则
type TOption = {
baseURL: string;
timeout: number;
};
//默认配置
const config = {
baseURL: "",
timeout: 30 * 1000,
withCredentials: true,
};
let loading:any = null;
class Http {
service: any;
constructor(config: TOption) {
//实例化请求配置
this.service = axios.create(config);
//请求拦截
this.service.interceptors.request.use(
(config: AxiosRequestConfig) => {
loading = ElLoading.service({ fullscreen: true,text:'加载中...' });
console.log(token.value);
if (token.value) {
(config.headers as AxiosRequestHeaders).authorization = token.value;
}
return config;
},
(error: any) => {
loading.close();
return Promise.reject(error);
}
);
//响应拦截
this.service.interceptors.response.use(
(response: AxiosResponse) => {
loading.close();
const data = response.data;
const { code } = data;
if (code == undefined) {
//如果没有返回状态码,直接返回数据,针对于返回数据为blob类型
return response;
} else if (code !== 0) {
ElMessage.error(data.message);
return Promise.reject(data);
}
// code == 0 的时候,提取我们只关注的Api数据data
return response.data.data;
},
(error: any) => {
loading.close();
ElMessage.error("请求失败:");
return Promise.reject(error);
}
);
}
get<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.get(url, { params, ...data });
}
post<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.post(url, params, data);
}
put<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.put(url, params, data);
}
delete<T>(
url: string,
params?: object,
data = {}
): Promise<IResponseData<T>> {
return this.service.delete(url, { params, ...data });
}
}
export default new Http(config);
3.使用fastmock,模拟后台数据传参
{
"code":0,
"message": "",
"data": [
{
"id": 1,
"name": "手机",
"img": "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/d764150a470174741d8b0b04515f7a78.jpg"
},
{
"id": 2,
"name": "平板",
"img":
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/d764150a470174741d8b0b04515f7a78.jpg"
},
{
"id": 3,
"name": "笔记本",
"img":
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/271ca8f503f72cfe33d282c74a499ebf.png"
}
]
}
4.Proxy配置
在vite.config.ts 文件中配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
port: 4000, // 你需要定义的端口号
// target:api地址
proxy: {
"/api": {
target: "https://www.fastmock.site/mock/15a3f8addfbc34c652777f67064eb49f/",
changeOrigin: true,
},
},
},
resolve: {
// 配置路径别名时,要安装npm install @types/node --save-dev
alias: {
'@': path.resolve(__dirname, './src'),
}
},
})
5.使用axios
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="#ID" width="60"> </el-table-column>
<el-table-column prop="name" label="名称" width="100">
<!-- scope代表的是当前列的填充数据 -->
<!-- 丰富table标签,用 <template #default="scope">标签进行扩展 -->
<template #default="scope">
<router-link :to="{ name: 'about', query: { id: scope.row.id } }">
{{ scope.row.name }}</router-link
>
</template>
</el-table-column>
<!-- contain图片等比例缩放 -->
<el-table-column prop="img" label="图片">
<template #default="scope">
<el-image
style="width: 100px; height: 100px"
:src="scope.row.img"
fit="contain"
/>
</template>
</el-table-column>
</el-table>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import http from "@/http/index";
//定义变量是需要用ref包裹一下
const tableData = ref([]);
//onMounted当页面加载时,显示数据
onMounted(() => {
http
.get("/api/products2")
.then((res: any) => {
tableData.value = res;
})
.catch((err: any) => {});
});
</script>
<style scoped>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
GitHub 加速计划 / vu / vue
207.55 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
更多推荐
已为社区贡献9条内容
所有评论(0)