Requirements:
1. In the initial state, the three buttons all display the number 0, and the text below reminds "0 means no calculation!";
2. Click any one of the three buttons below, the number in the button will be +1, and the sum of the three numbers will be automatically calculated below;
3. It is required to use the calculated properties and listening properties of Vue.js to implement the above functions respectively; except for buttons that can be bound to functions, the calculation function does not allow the use of function methods; 4. The two
implementation methods are written on the same page;
Answer:
<!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>