Vue和Flask通信的實(shí)現(xiàn)
這里我們通過axios來連接Vue前端和Flask后端,使用AJAX請(qǐng)求進(jìn)行通信。使用如下命令安裝
npm install axios
axios的使用格式:
import axios from ’axios’; export default { data: function () { return {serverResponse: ’res_test’ }; }, methods: { getData() {// 設(shè)置對(duì)應(yīng)python的接口,這里使用的是localhost:5000const path = ’http://127.0.0.1:5000/getMsg’;// 這里要使用 res =>表示返回的數(shù)據(jù)axios.get(path).then(res => { // 這里服務(wù)器返回response為一個(gè)json對(duì)象 // 通過.data來訪返回的數(shù)據(jù),然后在通過.變量名進(jìn)行訪問 // 可以直接通過response.data取得key-value var msg = res.data.msg; this.serverResponse = msg; // 因?yàn)椴荒苤苯邮褂胻his作為指針,因此在這之前將this賦給了then指針 alter(’Success’ + response.status + ’,’ + response.data + ’,’ + msg); // 成功后顯示提示}).catch(error => { console.error(error);}); } }, }代碼及演示前端代碼
對(duì)./components/HelloWorld.vue文件進(jìn)行改寫。代碼如下:
<!-- html部分 --><template> <div> <span>{{ serverResponse }}</span> <!--這里使用{{}}來引用JavaScript中賦給this的值--> <button @click='getData'>get data</button> </div></template><!-- js部分 --><script> import axios from ’axios’; export default { data: function () { return {serverResponse: ’res_test’ }; }, methods: { getData() {// 設(shè)置對(duì)應(yīng)python的接口,這里使用的是localhost:5000const path = ’http://127.0.0.1:5000/getMsg’;axios.get(path).then(res => { // 這里服務(wù)器返回response為一個(gè)json對(duì)象 // 通過.data來訪返回的數(shù)據(jù),然后在通過.變量名進(jìn)行訪問 // 可以直接通過response.data取得key-value var msg = res.data.msg; this.serverResponse = msg; // 因?yàn)椴荒苤苯邮褂胻his作為指針,因此在這之前將this賦給了then指針 alter(’Success’ + response.status + ’,’ + response.data + ’,’ + msg); // 成功后顯示提示}).catch(error => { console.error(error);}); } }, }</script><!-- css部分 --><!-- Add 'scoped' attribute to limit CSS to this component only --><style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; }</style>
這里主要實(shí)現(xiàn)了通過單擊按鈕來和服務(wù)器端進(jìn)行交互獲得數(shù)據(jù)并傳回前端,將得到的數(shù)據(jù)重新來對(duì)前端進(jìn)行渲染。
得到如上頁面之后,我們單擊get date按鈕,就會(huì)像后端發(fā)送GET請(qǐng)求,后端服務(wù)器監(jiān)聽到請(qǐng)求之后就會(huì)返回對(duì)應(yīng)的數(shù)據(jù)。
from flask import Flaskfrom flask import jsonifyfrom flask_cors import CORSapp = Flask(__name__)cors = CORS(app, resources={r'/getMsg': {'origins': '*'}})@app.route(’/’)def hello_world(): return ’test!’# 監(jiān)聽127.0.0.1:5000/getMsg請(qǐng)求@app.route(’/getMsg’, methods=[’GET’, ’POST’])def home(): response = {’msg’: ’Hello, Python !’ } return responseif __name__ == ’__main__’: app.run()
到此這篇關(guān)于Vue和Flask通信的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue和Flask通信內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. 詳解idea中web.xml默認(rèn)版本問題解決3. JSP頁面實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法5. jsp EL表達(dá)式詳解6. asp知識(shí)整理筆記4(問答模式)7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)9. java 優(yōu)雅關(guān)閉線程池的方案10. Python matplotlib 繪制雙Y軸曲線圖的示例代碼
