vue2调用接口
初见vue2,试探了两天,第一次正经接触前端,蛮兴奋的。
创建接口
import uvicorn
from fastapi import FastAPI, Header
from typing import Union
from typing_extensions import Annotated
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# 这一块是为了 vue2 能够跨域访问
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/read")
async def read(Authorization: Annotated[Union[str, None], Header()] = None):
if Authorization == 'SG68ER4G68SE1F':
return {
"List": [
"{\"dep\": \"ANY\", \"arr\": \"YOU\", \"depTime\": \"2021-05-21 13:14\", \"arrTime\": \"2021-05-20 13:14\", \"flightNum\": \"AN2199\", \"email\": \"demo@anyi.com\", \"persioner\": \"anyiya/lake\", \"date\": \"2023-08-10 15:58:35\"}",
"{\"dep\": \"ANY\", \"arr\": \"YOU\", \"depTime\": \"2021-05-21 13:14\", \"arrTime\": \"2021-05-20 13:14\", \"flightNum\": \"AN2199\", \"email\": \"demo@anyi.com\", \"persioner\": \"anyiya/lake\", \"date\": \"2023-08-10 15:58:35\"}",
"{\"dep\": \"ANY\", \"arr\": \"YOU\", \"depTime\": \"2021-05-21 13:14\", \"arrTime\": \"2021-05-20 13:14\", \"flightNum\": \"AN2199\", \"email\": \"demo@anyi.com\", \"persioner\": \"anyiya/lake\", \"date\": \"2023-08-10 15:58:33\"}",
"{\"dep\": \"ANY\", \"arr\": \"YOU\", \"depTime\": \"2021-05-21 13:14\", \"arrTime\": \"2021-05-20 13:14\", \"flightNum\": \"AN2199\", \"email\": \"demo@anyi.com\", \"persioner\": \"anyiya/lake\", \"date\": \"2023-08-10 15:58:32\"}"
]
}
else:
return False
lock = "lock"
@app.get("/unlock")
async def unlock(Authorization: Annotated[Union[str, None], Header()] = None):
if Authorization == 'SG68ER4G68SE1F':
global lock
lock = "unlock"
return True
else:
return False
@app.get("/relock")
async def relock(Authorization: Annotated[Union[str, None], Header()] = None):
if Authorization == 'SG68ER4G68SE1F':
return lock
else:
return False
@app.get("/now")
async def getnow(Authorization: Annotated[Union[str, None], Header()] = None):
if Authorization == 'SG68ER4G68SE1F':
return {"status": "2021-05-20 13:19:23 4. In the sky"}
else:
return False
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=9876)
部署vue2
# 克隆项目
git clone https://github.com/PanJiaChen/vue-admin-template.git
# 进入项目目录
cd vue-admin-template
# 安装依赖
apt install -y npm
npm install
# 建议不要直接使用 cnpm 安装以来,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题
npm install --registry=https://registry.npm.taobao.org
# 安装请求接口需要的依赖
npm install qs -S
npm install axios -S
# 启动服务
npm run dev
# 默认地址
http://ip:9528
文件目录
简单了解下文件目录,方便我们接下来“调参”
- vue-base 项目名称
- node_modules 项目依赖模块,一般不修改
- public 单入口文件index.html 在项目打包webpack的直接打包到dist文件里
- src 前端要写的文件 -资源文件
- assets 静态资源 css、js、images...
- components 公共组件
- App.vue 根组件
- main.js 核心入口文件 配置(挂载vue实例)
- router 配置路由
- views 编辑所有组件
- api 接口请求文件
我们图快
- src/main.js 下导入包
import Axios from 'axios'
import qs from 'qs'
Vue.prototype.axios = Axios //全局注册,使用方法为:this.$axios
Vue.prototype.qs = qs //全局注册,使用方法为:this.qs
-
src/router/index.js 下增加页面
-
scr/views 下创建对应路径与index.vue
-
简单了解一下index.vue,包含三个模块
- template 其中写 html
- script 其中写js
- style 其中写css
index.vue
<template>
<div>
<!-- 1. 当前状态 -->
<div class="status-container" v-if="apiResponse">
<transition name="fade-slide">
<p class="status-data">当前进度:{{ apiResponse }}</p>
</transition>
</div>
<!-- 2. 飞行列表 -->
<el-table :data="list" border highlight-current-row>
<el-table-column align="center" label="序号" width="60">
<template slot-scope="scope">
{{ scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column align="center" label="起飞地" width="90">
<template slot-scope="scope">
{{ scope.row.dep }}
</template>
</el-table-column>
<el-table-column align="center" label="目的地" width="90">
<template slot-scope="scope">
{{ scope.row.arr }}
</template>
</el-table-column>
<el-table-column align="center" label="起飞时间" width="180">
<template slot-scope="scope">
{{ scope.row.depTime }}
</template>
</el-table-column>
<el-table-column align="center" label="航班号" width="150">
<template slot-scope="scope">
{{ scope.row.flightNum }}
</template>
</el-table-column>
<el-table-column align="center" label="旅客名">
<template slot-scope="scope">
{{ scope.row.persioner }}
</template>
</el-table-column>
<el-table-column align="center" label="邮箱号" width="300">
<template slot-scope="scope">
{{ scope.row.email }}
</template>
</el-table-column>
<el-table-column align="center" label="入队时间" width="180">
<template slot-scope="scope">
{{ scope.row.date }}
</template>
</el-table-column>
</el-table>
<!-- 3. 解锁操作 -->
<div class="api-requests-container">
<el-button type="primary" @click="unlockData" class="unlock-button">解锁</el-button>
</div>
<div class="result-container" v-if="showResult">{{ result }}</div>
</div>
</template>
<script>
export default {
name: 'maincomponent',
//这里声明返回变量
data() {
return {
list: null,
apiResponse: "测试状态声明",
result: null,
showResult: false,
};
},
//这里放预加载函数
mounted: function () {
var that = this
this.axios({
method: 'get',
headers: {
'ContentType': 'application/json',
'Accept': '*/*',
'Authorization': 'SG68ER4G68SE1F',
},
dataType: 'json',
ContentType: 'application/json;charset-utf-8',
url: 'http://127.0.0.1:9876/read',
data: {}
}).then(function (response) {
console.log('数据列表:', response);
const data = response.data.List.map(item => JSON.parse(item)); // Parse JSON strings into objects
that.list = data;
console.log(data);
}).catch(function (error) {
console.log(error);
});
this.axios({
method: 'get',
headers: {
'ContentType': 'application/json',
'Accept': '*/*',
'Authorization': 'SG68ER4G68SE1F',
},
dataType: 'json',
ContentType: 'application/json;charset-utf-8',
url: 'http://127.0.0.1:9876/now',
data: {}
}).then(function (response) {
console.log('状态数据', response);
that.apiResponse = response.data.status;
}).catch((error) => {
console.log(error);
this.apiResponse = 'An error occurred while fetching data.';
});
},
//这里放需要事件触发的函数
methods: {
unlockData() {
this.axios({
method: 'get',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
'Authorization': 'SG68ER4G68SE1F',
},
dataType: 'json',
ContentType: 'application/json;charset-utf-8',
url: 'http://127.0.0.1:9876/unlock', // Modify the URL accordingly
data: {},
}).then((response) => {
if (response.data === true) {
this.result = '解锁成功';
} else {
this.result = '解锁失败';
}
this.showResult = true; // 显示结果
setTimeout(() => {
this.showResult = false; // 隐藏结果
}, 3000); // 3秒后隐藏
}).catch((error) => {
console.log(error);
this.result = '操作出错'
this.showResult = true; // 显示结果
setTimeout(() => {
this.showResult = false; // 隐藏结果
}, 3000); // 3秒后隐藏
});
},
}
}
</script>
<style scoped>
/* 解锁结果 */
.result-container {
position: fixed;
top: 50%;
/* 将容器顶部放置在屏幕中间 */
left: 50%;
/* 将容器左侧放置在屏幕中间 */
transform: translate(-50%, -50%);
/* 居中对齐 */
color: black;
font-size: 30px;
}
/* 解锁按钮 */
.content {
/* 设置内容区域的样式,以留出足够的空间给按钮 */
padding: 20px;
}
.api-requests-container {
display: flex;
justify-content: flex-end;
/* 将内容放置在容器的右边 */
align-items: flex-end;
/* 垂直居底对齐 */
height: 15vh;
/* 使用视口高度来撑开容器 */
position: fixed;
top: 0;
right: 0;
padding: 20px;
/* 距离右边和底部的内边距 */
}
/* 当前状态滑动条 */
.status-container {
display: flex;
align-items: center;
}
.status-data {
/* flex: 1; */
font-size: 30px;
display: inline-block;
overflow: hidden;
white-space: nowrap;
animation: slide 60s infinite;
}
@keyframes slide {
0%,
100% {
transform: translateX(10%);
}
50% {
transform: translateX(50%);
}
}</style>