使用Vue製作簡單的計算器

跟着Vue官網的教程學了一下,對Vue有了一個初步的瞭解,通過製作簡單的計算器來練習一下,主要是通過switch判斷。效果如下:

在這裏插入圖片描述
源碼:

<!DOCTYPE html>
<html>
<head>
  <title>practice_01</title>
</head>
<body>
  <div id="app">
    <h3>簡單計算器</h3>
    <input type="text" v-model.number="first">
    <select v-model="selected">
      <option disabled value="">請選擇</option>
      <option value="0">+</option>
      <option value="1">-</option>
      <option value="2">*</option>
      <option value="3">/</option>
    </select>
    <input type="text" v-model.number="two">
    <input type="button" @click="equal" value="=">
    <input type="text" v-model.number="three">
  </div>
  <!-- 引入vue.js -->
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script type="text/javascript">
    var vm = new Vue({
      el: '#app',
      data: {
        first: '', //第一個數
        two: '', //第二個數
        three: '', //結果
        selected: "", //符號
      },
      methods: {
        equal: function() {
          switch(this.selected){
          //使用switch來判斷
            case '0':
                this.three = this.first + this.two
                break;
            case '1':
                this.three = this.first - this.two
                break;
            case '2':
                this.three = this.first * this.two
                break;
            case '3':
                this.three = this.first / this.two
                break;
          }
        }
      }
    })
  </script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章