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 CORS
app = 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}), 200
if __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 CORS
app = 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}), 200
if __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 CORS
app = Flask(__name__)
CORS(app)
@app.route('/api/data', methods=['GET'])
def get_data():
# 假设这是从数据库或其他地方获取的数据
data = {
'name': 'John Doe',
'age': 30
}
return jsonify(data), 200
if __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-menu
active-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进口路由包
=========================================================