当前位置: 首页 > news >正文

Vue+Flask

App.vue

首先要安装

npm install axios
<template><div><h1>{{ message }}</h1><input v-model="name" placeholder="Enter your name" /><input v-model="age" placeholder="Enter your age" /><button @click="sendData">Send Data</button></div>
</template><script>
import axios from 'axios';export default {data() {return {message: 'Please enter your details',name: '',age: ''};},methods: {async sendData() {const payload = {name: this.name,age: this.age};try {const response = await axios.post('http://localhost:5000/api/data', payload);this.message = response.data.message;  // 更新消息} catch (error) {console.error('Error sending data:', error);}}}
};
</script><style scoped>
/* 样式 */
input {margin: 5px;
}
button {margin-top: 10px;
}
</style>

flask

from flask import Flask, jsonify, request
from flask_cors import CORSapp = Flask(__name__)
CORS(app)@app.route('/api/data', methods=['POST'])
def post_data():data = request.json  # 获取请求中的 JSON 数据print(data)  # 打印数据return jsonify({'message': 'Data received!', 'data': data}), 200if __name__ == '__main__':app.run()

进阶============================================

<template><div><h1>{{ message }}</h1><input v-model="name" placeholder="Enter your name" /><input v-model="age" placeholder="Enter your age" /><button @click="sendData">Send Data</button><!-- 新增的文本字段 --><div v-if="receivedData"><h2>Received Data:</h2><p>Name: {{ receivedData.name }}</p><p>Age: {{ receivedData.age }}</p></div></div>
</template><script>
import axios from 'axios';export default {data() {return {message: 'Please enter your details',name: '',age: '',receivedData: null // 新增用于存储接收到的数据};},methods: {async sendData() {const payload = {name: this.name,age: this.age};try {const response = await axios.post('http://localhost:5000/api/data', payload);this.message = response.data.message;  this.receivedData = response.data.data; // 假设后端返回的数据结构为 { message: '...', data: { name: '...', age: '...' } }} catch (error) {console.error('Error sending data:', error);}}}
};
</script><style scoped>
/* 样式 */
input {margin: 5px;
}
button {margin-top: 10px;
}
</style>
from flask import Flask, jsonify, request
from flask_cors import CORSapp = Flask(__name__)
CORS(app)@app.route('/api/data', methods=['POST'])
def post_data():data = request.json  # 获取请求中的 JSON 数据print(data)  # 打印数据data={"name":'你好','age':999}return jsonify({'message': 'Data received!', 'data': data}), 200if __name__ == '__main__':app.run()

===================GET方法==============================

<template><div><h1>{{ message }}</h1><button @click="fetchData">Fetch Data</button><!-- 新增的文本字段 --><div v-if="receivedData"><h2>Received Data:</h2><p>Name: {{ receivedData.name }}</p><p>Age: {{ receivedData.age }}</p></div></div>
</template><script>
import axios from 'axios';export default {data() {return {message: 'Click the button to fetch data',receivedData: null // 用于存储接收到的数据};},methods: {async fetchData() {try {const response = await axios.get('http://localhost:5000/api/data'); // 发送 GET 请求this.receivedData = response.data; // 假设后端返回的数据直接是 { name: '...', age: '...' }} catch (error) {console.error('Error fetching data:', error);}}}
};
</script><style scoped>
/* 样式 */
button {margin-top: 10px;
}
</style>
from flask import Flask, jsonify
from flask_cors import CORSapp = Flask(__name__)
CORS(app)@app.route('/api/data', methods=['GET'])
def get_data():# 假设这是从数据库或其他地方获取的数据data = {'name': 'John Doe','age': 30}return jsonify(data), 200if __name__ == '__main__':app.run(debug=True)

导航栏+子页面结构=======================================

结构

src

router(跳转页面的路由设置index.js)

view(跳转页面的视图PageOne.vue)

components(导航栏的组件)

App.vue

main.js

=========================================================

router(跳转页面的路由设置index.js)

配置index.js

创建路由{路由历史,路由{路由映射,组件地址}}

然后默认导出路由

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';// 导入你的页面组件
import Page1 from '../views/PageOne.vue';
const routes = [{ path: '/page1', component: Page1 },{ path: '/', redirect: '/page1' }  // 默认重定向
];const router = createRouter({history: createWebHistory(),routes,
});export default router;

=========================================================

Aview视图

PageOne.vue

<template><div class="page"><h1>欢迎来到页面一</h1><p>这是你的应用程序的第一个页面。</p><p>这里有一些有趣的事实:</p><ul><li>Vue.js 是一个渐进式的 JavaScript 框架,用于构建用户界面。</li><li>它的设计初衷是可以逐步适应不同需求。</li><li>Vue 的核心库仅关注视图层。</li></ul><button @click="goToPage2">前往页面二</button></div>
</template><script>
export default {name: 'PageOne', // 修改为多单词名称methods: {goToPage2() {this.$router.push('/page2'); // 跳转到页面 2}}
};
</script><style scoped>
.page {text-align: center;padding: 20px;
}
h1 {color: #42b983;
}
</style>

=========================================================

App.vue

YourMenuComponent.vue是左侧导航栏

el-row是行    el-col是宽

<template><el-row><el-col :span="7"><YourMenuComponent /></el-col><el-col :span="17"><router-view /></el-col></el-row>
</template><script setup>
import YourMenuComponent from './components/YourMenuComponent.vue';
</script><style>
/* 可根据需要添加样式 */
</style>

=========================================================

components(导航栏的组件)

<router-link to="/page1">

<template><el-row class="tac"><el-col :span="10"><h5 class="mb-2">Custom colors</h5><el-menuactive-text-color="#ffd04b"background-color="#545c64"class="el-menu-vertical-demo"default-active="1-1"text-color="#fff"@open="handleOpen"@close="handleClose"><el-sub-menu index="1"><template #title><el-icon><location /></el-icon><span>Navigator One</span></template><el-menu-item-group title="Group One"><el-menu-item index="1-1"><router-link to="/page1">Item One</router-link></el-menu-item><el-menu-item index="1-2"><router-link to="/page2">Item Two</router-link></el-menu-item></el-menu-item-group><!-- 其他菜单项 --></el-sub-menu><el-menu-item index="2"><el-icon><icon-menu /></el-icon><router-link to="/page2">Navigator Two</router-link></el-menu-item><el-menu-item index="3" disabled><el-icon><document /></el-icon><span>Navigator Three</span></el-menu-item><el-menu-item index="4"><el-icon><setting /></el-icon><router-link to="/page4">Navigator Four</router-link></el-menu-item></el-menu></el-col></el-row></template><script setup>import { Menu as IconMenu, Setting } from '@element-plus/icons-vue';const handleOpen = (key, keyPath) => {console.log(key, keyPath);};const handleClose = (key, keyPath) => {console.log(key, keyPath);};</script>

=========================================================

main.js

在使用 app.use(router); 后,路由功能就可以在整个 Vue 应用中全局使用,任何组件都可以使用 <router-link> 进行路由导航,或者使用 this.$router 访问路由实例。

import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 引入 router
import ElementPlus from 'element-plus'; // 引入 Element Plus
import 'element-plus/dist/index.css'; // 引入 Element Plus 的样式const app = createApp(App);
app.use(router); // 使用 router
app.use(ElementPlus); // 使用 Element Plus
app.mount('#app'); // 挂载应用

=========================================================

原理结论 先在view创建一个pageone.vue 出口----->设置路由pageone.vue组件的路由地址 出口路由包------>main.js进口路由包

=========================================================

http://www.lryc.cn/news/450597.html

相关文章:

  • 深入剖析 Android Lifecycle:构建高效稳定的应用
  • ElasticSearch分词器、相关性详解与聚合查询实战
  • 删除二叉树中以x为根节点的子树(包括根结点)
  • Netty 与 WebSocket之间的关系
  • 通信工程学习:什么是CSMA/CA载波监听多路访问/冲突避免
  • JAVA并发编程系列(13)Future、FutureTask异步小王子
  • 【python爬虫可以获取到谷歌影像吗?】如何有效下载谷歌影像?
  • Windows 上安装 PostgreSQL
  • Vue 技术进阶 day2 数据监视的原理、其他内置指令、自定义指令、生命周期、组件化、VueComponent构造函数
  • vue.js 原生js app端实现图片旋转、放大、缩小、拖拽
  • MyBatis的注入问题
  • 基于springboot的评分评教管理系统
  • C嘎嘎入门篇:类和对象(2)
  • 数据库 - Mongo数据库
  • 工业控制过等保三级需要的网络安全设备及详细讲解
  • Android开发高级篇:MVVM框架与数据双向绑定
  • 智能招聘系统小程序的设计
  • Wireshark抓包GRPC协议查看Protobuf编码内容
  • selenium 强制、隐式、显示等待(11种预置条件)
  • ffmpeg拉取rtsp网络视频流报错解析
  • c# iTextSharp 读取PDF
  • <<迷雾>> 第5章 从逻辑学到逻辑电路(3)--与门 示例电路
  • Java应用的数据库连接池连接超时处理
  • 机器学习:opencv--摄像头OCR
  • 基于二分查找的动态规划 leetcode 300.最长递增子序列
  • Java8 IntStream流sum的Bug
  • PCL 索引空间采样
  • PasteForm最佳CRUD实践,实际案例PasteTemplate详解之3000问(三)
  • 【无标题】logistic映射
  • 基于Node.js+Express+MySQL+VUE科研成果网站发布查看科研信息科研成果论文下载免费安装部署