我是 Vue.js 的新手,仍在练习所有功能。我想知道如何根据这段代码编写可重用的递增和递减函数——这就是我现在所拥有的,但它是重复的。所以我想对两个不同的按钮使用递增/递减功能。 Here's jsfiddle demo!
new Vue ({
el: "#pomodoro-clock",
data: {
breakLength: 5,
sessionLength: 25,
},
methods: {
addBreak: function(inc){
this.breakLength += inc;
},
subtractBreak: function(dec){
if(this.breakLength === 1) return;
this.breakLength -= dec;
},
addSession: function(inc){
this.sessionLength += inc;
},
subtractSession: function(dec){
if(this.sessionLength === 1) return;
this.sessionLength -= dec;
}
}
});
最佳答案
这是可重用方法的示例。
methods: {
inc(property, amt){
this[property] += amt
},
dec(property, amt){
if (this[property] === 1) return
this[property] -= amt
},
...
}
在你的模板中:
<span class="clock__btn--add" v-on:click="inc('breakLength', 1)">+</span>
<span class="clock__break-length">{{breakLength}}</span>
<span class="clock__btn--subtract" v-on:click="dec('breakLength', 1)">-</span>
已更新 fiddle .
关于javascript - Vue.js 中可重用的递增和递减函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45654205/