Vue计算器 使用Vue实现简单计算器

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue计算器 使用Vue实现简单计算器

aProgrammerWithDream   2021-04-21 我要评论

使用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>

运行结果如下:

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们