There is an input form to enter numbers and a Selectbox to select its unit. I want to make it impossible to select a unit when no number is entered, and to clear the value of the Selectbox when the number is erased after the unit is selected.
<div>
<input-number v-model="number" />
<select v-model="unit" :disabled="!form.model.number">
<select-option v-for="item in currency_unit">
{{ item.name }}
</select-option>
</select>
</div>
CodePudding user response:
Remember to add a :key directive every time you iterate something.
<template>
<div>
<input number v-model="number" />
<select v-model="unit" :disabled="!number">
<option v-for="item in currency_unit" :key="item.id">
{{ item.name }}
</option>
</select>
</div>
</template>
To clear the unit value you can use watcher
<script>
export default {
name: 'Component',
data() {
return {
number: '',
unit: null,
currency_unit: [
{ name: 'foo', id: 1 },
{ name: 'bar', id: 2 },
],
};
},
watch: {
number(newValue) {
if (!newValue) {
this.unit = null;
}
},
},
};
</script>
CodePudding user response:
Modify the disable condition to be number === ''
and set the initial value of number
as ''
var app = new Vue({
el: '#app',
data() {
return {
number: '',
unit: null,
currency_unit: [
{ id: 'rupee', name: 'Rupees'},
{ id: 'dollar', name: 'Dollars'},
{ id: 'euro', name: 'Euros'}
]
};
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input number v-model="number" />
<select v-model="unit" :disabled="number===''">
<option v-for="item in currency_unit" :key="item.id">
{{ item.name }}
</option>
</select>
</div>
CodePudding user response:
To achieve this, You can put a watcher
on number
model value. So that if it gets empty you can assign an empty or null value to unit
.
Live Demo :
new Vue({
el: '#app',
data: {
number: null,
unit: null,
currency_unit: [{
name: 'A'
}, {
name: 'B'
}, {
name: 'C'
}]
},
watch: {
number(val) {
if (!val) {
this.unit = null;
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<input type="number" v-model="number" />
<select v-model="unit" :disabled="!number">
<option v-for="(item, index) in currency_unit" :key="index">
{{ item.name }}
</option>
</select>
</div>