赞
踩
1、前端框架:
vue:前端开发框架
vuex:前端数据仓库,用于数据存储
axios:前端网络请求库,用于发http/https请求
element:前端UI控件
2、后端框架:
flask:轻量级python web框架
----------------------------------------------------------
在前端代码,App.vue文件的<!--展示模板--><template>,引入elementUI,例如:
- <form action = "">
- <p>请输入通知消息:</p>
- <p><input type = "text" v-model="formMessage.message"/></p>
- </form>
- <el-button type="primary" @click="getBackend">提交到后端</el-button>
- <el-input
- type="textarea"
- :rows="2"
- placeholder="请输入内容"
- v-model="textarea">
- </el-input>
然后在<script>,将elementUI的数据进行获取,并传给axios发请求,然后通过vuex存储数据,再通过vuex把数据给到前端的文本域控件利用v-model进行回显:
store.js代码:
- import Vue from "vue";
- import Vuex from "vuex";
-
- Vue.use(Vuex)
-
- const store = new Vuex.Store({
- state: {
- backendData:'x'
- },
- mutations: {
- set_backdata(state, data) {
- state.backendData = data
- }
- },
- actions:{
- get_backdata({ commit }, value) {
- commit('set_backdata', value);
- // commit('SET_TOKEN', value2)
- }
- },
- getters: { //数据处理or计算
- bkdata(state){
- return state.backendData;
- }
- }
- })
- export default store;
App.vue代码:
- <script>
- //导入组件
- import HelloWorld from './components/HelloWorld.vue'
- import axios from "axios";
-
- export default {
- name: 'App',
- components: {
- HelloWorld
- },
- data() {
- return {
- textarea: "",
- formMessage:{
- "message":""
- }
- }
- },
- computed:{
- returnData(){
- return this.$store.getters.bkdata
- }
- },
- created(){
- // this.getBackend()
- },
- methods: {
- getBackend() {
- const url = "http://127.0.0.1:5000/guest/" + this.$data.formMessage.message;
-
- axios.get(url)
- .then((res) => {
- this.$store.dispatch('get_backdata',res.data) //将后端数据存储到vuex里
- this.textarea=this.returnData
- })
- .catch((error) => {
- console.log(error);
- })
- }
- }
- }
- </script>
由于前后端的端口不同,以及将来独立部署的域名也不同,后端flask需要进行跨域处理(test.py):
- from flask import Flask, redirect, url_for, request
- from flask_cors import CORS
-
- app = Flask(__name__)
- # 跨域
- CORS(app)
-
-
- @app.route('/')
- def hello_world():
- return 'Hello World'
-
-
- @app.route('/guest/<guest>')
- def hello_guest(guest):
- return 'Hello %s as Guest' % guest
-
-
- @app.route('/user/<name>')
- def hello_user(name):
- if name == 'admin':
- return redirect(url_for('hello_world admin'))
- else:
- return redirect(url_for('hello_guest', guest=name))
-
-
- @app.route('/success/<name>')
- def success(name):
- return 'welcome %s' % name
-
-
- @app.route('/login', methods=['POST', 'GET'])
- def login():
- if request.method == 'POST':
- user = request.form['nm']
- return redirect(url_for('success', name=user))
- else:
- user = request.args.get('nm')
- return redirect(url_for('hello_user', name=user))
-
-
- if __name__ == '__main__':
- app.run()
实现效果:
有任何疑问欢迎留言交流~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。