好像不加watch也可以完成效果

来源:3-23 自由编程

Ting111

2021-01-05 20:21:37

<!DOCTYPE html>

<html lang="en">


<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title></title>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>


  

</head>


<body>

  <div id='app'> 

 <input type='text' v-model.number='num1' />

 <select v-model='count'>

   <option>+</option>

   <option>-</option>

   <option>*</option>

   <option>/</option>

 </select>

<input  type='text' v-model.number='num2'  />

<button @click='result'>=</button>

<input  type='text' v-model.number='res' />


</div>

<script>

var counting=new Vue({

  el:'#app',

  data:{

    num1:'',

    num2:'',

    res:'',

    count:'',

  },

  methods:{

    result:function(){

      this.resolution();

    }

    

  },

  computed:{

    resolution:function(){

      switch(this.count){

        case '+':

          this.res=this.num2+this.num2;

          break;

        case '-':

          this.res=this.num1-this.num2;

          break;

        case '*':

          this.res=this.num1*this.num2;

          break;

        case '/':

          this.res=num1/this.num2;

          break;

      }

    }

  }

})



 






</script>




</body>


</html>


写回答

1回答

好帮手慕久久

2021-01-06

同学你好,同学的代码运行后,有报错,如下:

http://img.mukewang.com/climg/5ff518a10943ae9908520257.jpg

报错是因为把计算属性当做方法来调用了,这种写法是错误的:

http://img.mukewang.com/climg/5ff516640918a8cf06740253.jpg

由于本题想要实现,切换运算符和点击“=”号,都能计算出结果,所以最好使用watch属性来实现,如下:

http://img.mukewang.com/climg/5ff5184b0918e49408730793.jpg

祝学习愉快!

0

0 学习 · 10739 问题

查看课程