Is there anyway to set a default value to an input to the value of another input field in case it has been left empty. Looks like I can't specify this in the data nor in the v-model attribute:
<template>
<div>
<input type="number" v-model="font1 || 14"> <!-- gives error -->
<input type="number" v-model="font2 || font1"> <!-- gives error -->
<input type="number" v-model="font3 || font1"> <!-- gives error -->
</div>
</template>
<script>
export default {
data() {
return {
font1: 14,
font2: this.font2 || this.font1, // this approach also gives error
font3: this.font3 || this.font1 // this approach also gives error
}
}
}
</script>
Any help is welcome. Thanks.
There is probably 37 different ways of doing it.
The question is what is important, robustness, maintainability, ease of implementation, scalability etc.
Here is a solution that prioritizes ease of implementation. It relies on using @change and :value instead of the v-model magic.
This will leave font2 and font3 as null if they are not changed.
new Vue({
el: '#app',
data: {
font1: 14,
font2: null,
font3: null,
},
methods: {
isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="number" v-model="font1">
<input type="number" @change="font2 = $event.target.value" :value="isNumber(font2)?font2:font1">
<input type="number" @change="font3 = $event.target.value" :value="isNumber(font3)?font3:font1">
<pre>{{ {font1:font1, font2:font2, font3:font3} }}</pre>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With