I have a Vue instance with five computed property functions that do the same things for different values. I repeat myself quite a bit and am wondering about a cleaner way to do this without repeating myself so much.
In the HTML template I have five input fields, each input field is limited to 25 characters and I would like to display I display a character counter:
<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>
I have five fields that look exactly like that except they say engraving.line2, engraving.line3, engraving.line4 and engraving.line5.
Then my component javascript I define the engraving object and have the same computed method for each field.
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";
}
},
How can I resuse this function to accept a data parameter and not repeat myself so much?