当前位置:   article > 正文

python后台vue3前端构建网站最简单示范_python vue3

python vue3

这里是一个简单的样本程序,使用 Vue 3 作为前端框架,Python 的 FastAPI 作为后端 API。首先,我们将创建一个 FastAPI 后端,然后使用 Vue 3 创建前端应用程序来调用后端 API。

后端:FastAPI

  1. 确保已安装 Python(3.7+)和 pip。
  2. 安装 FastAPI 和 Uvicorn:
   pip install fastapi uvicorn
  • 1
  1. 创建一个名为 main.py 的 Python 文件,内容如下:
   from fastapi import FastAPI

   app = FastAPI()

   @app.get("/api/message")
   async def get_message():
       return {"message": "Hello from FastAPI!"}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 使用 Uvicorn 运行后端:
   uvicorn main:app --reload --host 0.0.0.0 --port 8000
  • 1

现在你的 FastAPI 后端已经在 http://localhost:8000 上运行了。

前端:Vue 3

  1. 确保已安装 Node.js 和 npm。
  2. 安装 Vue CLI:
   npm install -g @vue/cli
  • 1
  1. 使用 Vue CLI 创建一个新的 Vue 3 项目:
   vue create frontend
  • 1

选择 Vue 3 作为默认框架,并继续安装过程。

  1. 进入项目目录并安装 Axios(用于调用 API):
   cd frontend
   npm install axios
  • 1
  • 2
  1. src 目录下创建一个名为 api.js 的文件,用于封装 API 调用:
   import axios from 'axios';

   const instance = axios.create({
       baseURL: 'http://localhost:8000/api',
   });

   export const getMessage = async () => {
       const response = await instance.get('/message');
       return response.data;
   };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. 打开 src/components/HelloWorld.vue 文件,将其修改为以下内容:
   <template>
     <div>
       <h1>{{ message }}</h1>
       <button @click="fetchMessage">Fetch Message</button>
     </div>
   </template>

   <script>
   import { ref } from 'vue';
   import { getMessage } from '../api';

   export default {
     name: 'HelloWorld',
     setup() {
       const message = ref('');
       const fetchMessage = async () => {
         const data = await getMessage();
         message.value = data.message;
       };
       return { message, fetchMessage };
     },
   };
   </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  1. 运行 Vue 项目:
   npm run serve
  • 1

现在你的 Vue 3 前端应用已经在 http://localhost:8080 上运行。点击 “Fetch Message” 按钮,你将看到从 FastAPI 后端 API 获取的消息。

请注意,为了在开发环境中避免跨域问题,你可能需要配置 Vue 开发服务器代理。在实际部署时,也需要确保 Vue 应用程序和 FastAPI 后端在同一个域上。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50018?site
推荐阅读
相关标签
  

闽ICP备14008679号