我有一个带有五个计算属性函数的Vue实例,它们对不同的值执行相同的操作。我重复了很多次,并且想知道一种更干净的方法来完成此操作,而不必重复太多次。
在HTML模板中,我有五个输入字段,每个输入字段限制为25个字符,我想显示的是我显示的字符计数器:
<div class='field is-grouped'>
<p class='control is-expanded'>
<input
class="input"
placeholder="Trophy engraving line 1 (25 character limit)"
v-model='engraving.line1'
v-validate="'required'"
:class="{'input': true, 'is-danger': errors.has('engraving.line1') }"
name='engraving.line1'>
</p>
<p class='control'>
<span>{{ line1count }}</span>
</p>
</div>
除了它们说
engraving.line2
,engraving.line3
,engraving.line4
和engraving.line5
之外,我有五个看起来完全一样的字段。然后,我的组件javascript将定义雕刻对象,并对每个字段使用相同的计算方法。
export default {
data(){
return {
engraving: {
line1: '',
line2: '',
line3: '',
line4: '',
line5: '',
}
};
},
computed: {
line1count() {
var chars = this.engraving.line1.length,
limit = 25;
return (limit - chars) + "/" + limit + " characters remaining";
},
line2count(){
var chars = this.engraving.line2.length,
limit = 25;
return (limit - chars) + "/" + limit + " characters remaining";
},
line3count(){
var chars = this.engraving.line3.length,
limit = 25;
return (limit - chars) + "/" + limit + " characters remaining";
},
line4count(){
var chars = this.engraving.line4.length,
limit = 25;
return (limit - chars) + "/" + limit + " characters remaining";
},
line5count(){
var chars = this.engraving.line5.length,
limit = 25;
return (limit - chars) + "/" + limit + " characters remaining";
}
},
如何重用此函数来接受数据参数,而又不用重复太多?
最佳答案
您可以使用一种方法:
methods: {
linecount(line, limit) {
var chars = this.engraving.line[line].length,
return (limit - chars) + "/" + limit + " characters remaining";
},
}
然后在您的html中引用它:
<p class='control'>
<span>{{ linecount(1,25) }}</span>
</p>
关于javascript - 如何在Vue计算属性中重用带有参数的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46694170/