先看代码:
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button @click="sub">-</button> <span>{{number}}</span> <button @click="add">+</button> </div> <script> var app = new Vue({ el: '#app', data: { number: 0 }, methods: { sub: function () { if (this.number != 0) { this.number -= 1; } else { alert("不能再减少了"); } }, add: function () { if (this.number < 10) { this.number += 1; } else { alert("不能再增加了"); } }, }, }) </script> </body> </html>
结果:
点击加号会一直增加数量,当加到10之后再点击:
点击减号可以减少数量,当数量为0时再点击: