引入vue文件
先用v-model指令将输入框与数据属性绑定在一起,再用双花括号语法将其显示出来。
创建一个 Vue 实例,定义数据属性,并重新定义选择数据计算属性。
效果图如下:
完整代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <script type="text/javascript" src="js/vue.js"></script>
- </head>
- <body>
- <div id="app">
- <input type="text" placeholder="输入第一个数" v-model.number="num1">
- <select v-model="sign">
- <option>+</option>
- <option>-</option>
- <option>*</option>
- <option>/</option>
- </select>
- <input type="text" placeholder="输入第二个数" v-model.number="num2"> <br> 答案:{{res}} <br>
- <input type="text" placeholder="输入第一个数" v-model.number="num3">
- <select v-model="sign1">
- <option>+</option>
- <option>-</option>
- <option>*</option>
- <option>/</option>
- </select>
- <input type="text" placeholder="输入第二个数" v-model.number="num4"> <br> 答案:{{res1}} <br>
- <input type="text" placeholder="输入第一个数" v-model.number="num5" @change="change">
- <select v-model="sign2" @change="change">
- <option>+</option>
- <option>-</option>
- <option>*</option>
- <option>/</option>
- </select>
- <input type="text" placeholder="输入第二个数" v-model.number="num6" @change="change"> <br> 答案:{{res2}}
- </div>
- <script>
- const vm = new Vue({
- el: "#app",
- data: {
- num1: 0,
- num2: 0,
- sign: "+",
- num3: 0,
- num4: 0,
- sign1: "+",
- res1: "",
- num5: 0,
- num6: 0,
- sign2: "+",
- res2: ""
- },
- methods: {
- change() {
- if(this.sign2 === "+") {
- this.res2 = this.num5 + this.num6;
- } else if(this.sign2 === "-") {
- this.res2 = this.num5 - this.num6;
- } else if(this.sign2 === "*") {
- this.res2 = this.num5 * this.num6;
- } else if(this.sign2 === "/") {
- this.res2 = this.num5 / this.num6;
- }
- }
- },
- computed: {
- res() {
- if(this.sign === "+") {
- return this.num1 + this.num2;
- } else if(this.sign === "-") {
- return this.num1 - this.num2;
- } else if(this.sign === "*") {
- return this.num1 * this.num2;
- } else if(this.sign === "/") {
- return this.num1 / this.num2;
- }
- }
- },
- watch: {
- num3(val) {
- if(this.sign1 === "+") {
- this.res1 = val + this.num4;
- } else if(this.sign1 === "-") {
- this.res1 = val - this.num4;
- } else if(this.sign1 === "*") {
- this.res1 = val * this.num4;
- } else if(this.sign1 === "/") {
- this.res1 = val / this.num4;
- }
- },
- num4(val) {
- if(this.sign1 === "+") {
- this.res1 = this.num3 + val;
- } else if(this.sign1 === "-") {
- this.res1 = this.num3 - val;
- } else if(this.sign1 === "*") {
- this.res1 = this.num3 * val;
- } else if(this.sign1 === "/") {
- this.res1 = this.num3 / val;
- }
- },
- sign1(val) {
- if(val === "+") {
- this.res1 = this.num3 + this.num4;
- } else if(val === "-") {
- this.res1 = this.num3 - this.num4;
- } else if(val === "*") {
- this.res1 = this.num3 * this.num4;
- } else if(val === "/") {
- this.res1 = this.num3 / this.num4;
- }
- }
- }
- })
- </script>
- </body>
- </html>