要求:
1、 初始状态下,三个按钮均显示数字 0,下方文字提醒“0 就不用计算啦!”;
2、 点击下方三个按钮中的任意一个,按钮中的数字会+1,下方自动计算出三个数字的和;
3、 要求分别使用 Vue.js 的计算属性和监听属性实现上述功能;除按钮可绑定函数外,计算功能不允许使用函数方法;
4、 两种实现方式写在同一个页面上;
答案:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<div>
<h2>Vue:计算属性实现简单计算功能</h2>
<button @click="add(1)">{{num1}}</button>
<button @click="add(2)">{{num2}}</button>
<button @click="add(3)">{{num3}}</button>
<p>{{getSum}}</p>
</div>
<div>
<h2>Vue:监听属性实现简单计算功能</h2>
<button @click="add(4)">{{num4}}</button>
<button @click="add(5)">{{num5}}</button>
<button @click="add(6)">{{num6}}</button>
<p>{{jiantingSum}}</p>
</div>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
num1: 0,
num2: 0,
num3: 0,
num4: 0,
num5: 0,
num6: 0,
jiantingSum: "0就不用计算了!"
},
methods: {
add(a) {
//如果是1号按钮,我应该操作num1 = num1 + 1
// num1 -> 'num' + a
var x = "num" + a
this[x]++
},
qiuhe (a, b, c) {
//如果传递进来的三个参数同时为0,返回不用计算了,否则返回求和结果
if (a == 0 && b == 0 && c == 0) {
return "0就不用计算了!"
} else {
var temp = a + b + c
return '求和结果:' + temp
}
}
},
computed: {
getSum() {
var t = this.qiuhe(this.num1, this.num2, this.num3)
return t
}
},
watch: {
num4() {
this.jiantingSum = this.qiuhe(this.num4, this.num5, this.num6)
},
num5() {
this.jiantingSum = this.qiuhe(this.num4, this.num5, this.num6)
},
num6() {
this.jiantingSum = this.qiuhe(this.num4, this.num5, this.num6)
}
}
});
</script>
</body>
</html>