1π
Try adding a v-on:change
event handler which deletes the unnecessary value.
new Vue({
el: "#app",
data: {
myFields: {
SelectedValue: ''
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="myFields.SelectedValue" v-on:change='delete myFields.favPHP'>
<option disabled value="">Choose a Programming language</option>
<option>PHP</option>
<option>Python</option>
<option>C#</option>
</select>
<input v-if="myFields.SelectedValue == 'PHP'" type="text" label="Your favorite version of PHP" v-model="myFields.favPHP">
<br>
<pre>
{{myFields}}
</pre>
</div>
0π
Native way to destroy property sure exist in JavaScript, itβs called delete operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete.
Your JS part would look like something:
new Vue({
el: "#app",
data: {
myFields:{
SelectedValue: '',
}
},
methods: {
deleteFavPhpField($event) {
if($event.target.value !== 'PHP')
delete this.myFields.favPHP;
}
}
})
And in HTML part you would add input
trigger on select element, like this:
<select v-model="myFields.SelectedValue" @change="deleteFavPhpField($event)">
But I would suggest another approach since delete
operator isnβt something that should be used easily. You can have you myFields.favPHP
field sett in data from beggining, and in <pre>
element you could display computed value, out of newFields
but without favPHP
if itβs empty. For example, you computed could be something like this:
computed: {
formattedFields() {
if(this.myFields.favPHP) return { ...this.myFields };
return {SelectedValue: this.myFields.SelectedValue}; // here you can use some iterator if you have more fields
}
}