Vue编写简易计算器

2025-12-17 06:33:18

1、引入vue.js

<head>


   <meta charset="UTF-8">
   <title>Vue简易计算器</title>
   <script src="../lib/vue.js"></script>
</head>

2、编写基本HTML结构

<div id="app">


   <input type="text" v-model="n1">
   <select name="" id="" 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="=" v-on:click="calc">
   <input type="text" v-model="result">
</div>

3、vue绑定对象

<script>


   var app = new Vue({
       el: '#app',
       data: {
           n1: '',
           n2: '',
           result: '',
           opt: '+'
       },
       methods: {
           calc() {
               //判断操作符
               switch (this.opt) {
                   case "+":
                       this.result = parseInt(this.n1) + parseInt(this.n2);
                       break;
                   case "-":
                       this.result = parseInt(this.n1) - parseInt(this.n2);
                       break;
                   case "*":
                       this.result = parseInt(this.n1) * parseInt(this.n2);
                       break;
                   case "/":
                       this.result = parseInt(this.n1) / parseInt(this.n2);
                       break;
               }  
           }
       }
   })
</script>

4、效果显示

Vue编写简易计算器

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢