Vue编写简易计算器

时间:2026-02-18 07:36:05

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编写简易计算器

© 2026 一点资料
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com