Vue学习笔记(九、简易计算器)
在这个案例中,我们使用v-model分别双向绑定了n1、n2操作数,op操作选项和result计算结果,同时用@绑定了等号按钮事件。
由于是双向绑定,当input和select通过外部输入内容时,vm内部的数值也会改变,所以calculate只计算内部这些变量就可以得到正确的结果。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>VueBaseCode</title><script src="./lib/vue.js"></script>
</head><body><div id="app"><input type="text" v-model="n1"><select v-model="op"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" v-model="n2"><input type="button" value="=" @click="calculate"><input type="text" v-model="result"></div><script>var vm = new Vue({el: '#app',data: {n1: 0,n2: 0,op: "+",result: 0},methods: {calculate() {switch (this.op) {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>
</body></html>
其实这里calculate方法也可以简写一下:
calculate() {this.result = eval(this.n1 + this.op + this.n2);
}
附:eval()函数接受一个字符串作为参数,并将这个字符串作为JavaScript代码来执行,可以用于用户动态输入执行代码或用于动态生成的代码段的执行,其执行的代码会在当前作用域中运行,这意味着它可以访问和修改当前作用域中的变量,其问题主要包含三个方面,1、又代码注入风险。2、性能差一些。3、可读性和维护性差一些。