使用Vue编写简单计算器

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/aManWithDreams/article/details/102749545

使用Vue编写简单计算器

  • 在Vue中,v-model 指令,可以实现表单元素和 Model 中数据的双向数据绑定,接下来,我们就用这个指令编写一个简单的计算器,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--计算器的显示结构-->
<div id="app">
    <input type="text" v-model="n1">
    <select v-model="opt">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
    </select>
    <input type="text" v-model="n2">
    <input type="button" value="=" @click="calculator">
    <input type="text" v-model="result">
</div>

<script>
    // 创建 Vue 实例,得到 ViewModel,简写vm
    var vm = new Vue({
        el: '#app',
        data: {
            n1: 0,
            n2: 0,
            opt: '+',
            result: 0
        },
        methods: {
            //计算的方法
            calculator() {
                switch (this.opt) {
                    case '+':
                        this.result = Number(this.n1) + Number(this.n2);
                        break;
                    case '-':
                        this.result = Number(this.n1) - Number(this.n2);
                        break;
                    case '*':
                        this.result = Number(this.n1) * Number(this.n2);
                        break;
                    case '/':
                        this.result = Number(this.n1) / Number(this.n2);
                        break;
                }
            }
        }
    });
</script>
</body>
</html>
  • 运行结果如下:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/aManWithDreams/article/details/102749545