windows10下,零基础学习VUE(3)-- axios+flask构建前后端通信demo

当前为大纲的内容:待完善中

1. axios

axios 安装

  • npm install axios

参考文档

示例demo

2. flask

构建api:

from flask import Flask, render_template,jsonify
from flask_cors import CORS
app = Flask(__name__,
        static_folder = "./dist/static",
        template_folder = "./dist")

cors = CORS(app, resources={"/api/*": {"origins": "*"}})

from random import *
@app.route('/api/random')
def random_number():
    response = {
        'randomNumber': randint(1, 100)
    }
    return jsonify(response)

在jupyter_notebook中运行服务

from werkzeug.serving import run_simple
run_simple('0.0.0.0', 9001, app)

3. 在vue中调用,并显示

    • 模板部分

      <template>
        <div>
          欢迎来到首个测试页面  
          <p>Random number from backend: {{ randomNumber }}</p>
          <button @click="getRandom">New random number</button>
          <p>{{orgdata}}</p>
          <foot-nav v-bind:class="{'isIndex':isIndexNow}"></foot-nav>
        </div>
      </template>    
    • js脚本部分

      <script>
        import FootNav from "../components/footer.vue";
        import axios from 'axios'
        export default {
          components: {
            FootNav
          },
          methods: {
            getRandomInt (min, max) {
              min = Math.ceil(min)
              max = Math.floor(max)
              return Math.floor(Math.random() * (max - min + 1)) + min
            },
            getRandom () {
              // this.randomNumber = this.getRandomInt(1, 100)
              this.randomNumber = this.getRandomFromBackend()
            },
            getRandomFromBackend () {
              const path = `http://localhost:9001/api/random`
              axios.get(path)
              .then(response => {
                this.randomNumber = response.data.randomNumber
                this.orgdata = response.data
              })
              .catch(error => {
                console.log(error)
              })
            }
          },
          data(){
            return{
              isIndexNow: true,
              randomNumber: 0,
              orgdata:null
            }
          }
        }
      </script>  
    • css脚本部分,未学习,不过就是页面丑一点而已,问题不大,回头再学把。
        原文作者:未命名
        原文地址: https://segmentfault.com/a/1190000018806490
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞