用python+vue实现一个计算页面

要实现一个计算器页面,我们需要分别创建前端和后端部分。前端使用 Vue.js 框架,后端使用 Python 的 Flask 框架。

安装依赖

bash 复制代码
pip install flask
npm install -g vue
npm install -g @vue/cli
vue create calculator-frontend
cd calculator-frontend
npm run serve

在 calculator-frontend 目录下创建一个名为 src 的文件夹,并在其中创建一个名为 Calculator.vue 的文件。将以下代码粘贴到该文件中:

html 复制代码
<template>
  <div id="app">
    <h1>简易计算器</h1>
    <input type="text" v-model="expression" />
    <button @click="calculate">计算</button>
    <p>结果: {{ result }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      expression: "",
      result: "",
    };
  },
  methods: {
    calculate() {
      this.$axios.post("http://localhost:5000/calculate", {
        expression: this.expression,
      }).then((response) => {
        this.result = response.data.result;
      });
    },
  },
};
</script>

在项目根目录下创建一个名为 backend.py 的文件,将以下代码粘贴到该文件中:

python 复制代码
from flask import Flask, request, jsonify
import ast
import operator

app = Flask(__name__)

@app.route("/calculate", methods=["POST"])
def calculate():
    expression = request.json["expression"]
    try:
        result = eval_expr(expression)
        return jsonify({"result": result})
    except Exception as e:
        return jsonify({"error": str(e)})

def eval_expr(expr):
    ops = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}
    node = ast.parse(expr, mode="eval")

    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        elif isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.BinOp):
            left = _eval(node.left)
            right = _eval(node.right)
            return ops[type(node.op)](left, right)
        else:
            raise TypeError(node)

    return _eval(node.body)

if __name__ == "__main__":
    app.run(debug=True)

运行后端服务器

python 复制代码
python backend.py

访问 http://localhost:8080,你将看到一个简单的计算器页面。在输入框中输入表达式,然后点击"计算"按钮,结果将显示在页面上。

相关推荐
_extraordinary_7 分钟前
Java 多线程(一)
java·开发语言
爱喝水的鱼丶16 分钟前
SAP-ABAP: ABAP ASSIGN COMPONENT 语句详解:动态字段符号的利器作用用法示例详解
运维·开发语言·sap·abap·开发经验·动态字段符号
一个java开发20 分钟前
distributed.client.Client 用户可调用函数分析
大数据·python
励志不掉头发的内向程序员20 分钟前
C++进阶——多态
开发语言·c++·学习
eqwaak031 分钟前
Matplotlib 动态显示详解:技术深度与创新思考
网络·python·网络协议·tcp/ip·语言模型·matplotlib
人工智能训练师33 分钟前
在Ubuntu中如何使用PM2来运行一个编译好的Vue项目
linux·运维·服务器·vue.js·ubuntu·容器
007php00744 分钟前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 将 Pandas DataFrame 转换为 Excel
python·json·excel·pandas·csv·aspose·dataframe
浩星1 小时前
iframe引入界面有el-date-picker日期框,点击出现闪退问题处理
前端·vue.js·elementui
flashlight_hi1 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode