用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,你将看到一个简单的计算器页面。在输入框中输入表达式,然后点击"计算"按钮,结果将显示在页面上。

相关推荐
Ralph_Y2 分钟前
多重继承与虚继承
开发语言·c++
__如风__10 分钟前
onlyoffice文档转换服务离线部署
python
今晚务必早点睡13 分钟前
写一个Python接口:发送支付成功短信
开发语言·python
weixin_5841214320 分钟前
vue内i18n国际化移动端引入及使用
前端·javascript·vue.js
jghhh0122 分钟前
基于C#实现与三菱FX系列PLC串口通信
开发语言·算法·c#·信息与通信
ada7_24 分钟前
LeetCode(python)22.括号生成
开发语言·数据结构·python·算法·leetcode·职场和发展
2501_9418714526 分钟前
面向微服务链路追踪与全局上下文管理的互联网系统可观测性设计与多语言工程实践分享
大数据·数据库·python
luoluoal26 分钟前
基于python的语音和背景音乐分离算法及系统(源码+文档)
python·mysql·django·毕业设计·源码
喵了meme30 分钟前
C语言实战练习
c语言·开发语言
imkaifan33 分钟前
bind函数--修改this指向,返回一个函数
开发语言·前端·javascript·bind函数