美文网首页
2019-06-02指令运用之简易计算器

2019-06-02指令运用之简易计算器

作者: 啊_6424 | 来源:发表于2019-06-02 12:44 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>简易计算器</title>
      <!-- 1。引入vue -->
      <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    
      <!-- 2.写一个挂载元素 -->
      <div id="app">
        <input type="text" v-model="operand1">
        <select name="oprator" v-model="operator">
          <option value="+">+</option>
          <option value="-">-</option>
          <option value="*">*</option>
          <option value="/">/</option>
        </select>
        <input type="text" v-model="operand2">
       <button @click="compute">=</button>
        <input type="text" readonly="readonly" v-model="result">
      </div>
    </body>
    </html>
    <script>
      // 3.new一个实例
      var vm = new Vue({
        el:"#app",
        data:{
          operand1:0,
          operand2:0,
          operator:"+",
          result:0,
    
        },
        methods:{
          compute:function(){
            console.log("计算方法");
            switch(this.operator){
              case "+":
                //这里不转为Number的话,就会当成字符串进行+ 操作,但其他操作还能正常运算
                this.result = parseInt(this.operand1) + parseInt(this.operand2);
                // this.result = this.operand1 - this.operand2;
                break;
              case "-":
                // this.result = parseInt(this.operand1) - parseInt(this.operand2);
                this.result = this.operand1 - this.operand2;
                break;
              case "*":
                // this.result = parseInt(this.operand1) * parseInt(this.operand2);
                this.result = this.operand1 * this.operand2;
                break;
              case "/":
                // this.result = parseInt(this.operand1) / parseInt(this.operand2);
                this.result = this.operand1 / this.operand2;
                break;
            }
          }
        }
      });
    </script>
    

    这样写代码量很大,改为如下:

    //注意这是投机取巧的方式,正式开发中少用
     compute:function(){
            console.log("计算方法");
            var codeStr = "parseInt(this.operand1)" + this.operator + "parseInt(this.operand2)";
            this.result = eval(codeStr);
          }
    

    相关文章

      网友评论

          本文标题:2019-06-02指令运用之简易计算器

          本文链接:https://www.haomeiwen.com/subject/uikxxctx.html