Vue js set a radio button checked if statement is true:To set a radio button as checked in Vue.js based on a condition, you can use the v-bind
directive to bind the checked
attribute of the input element to a data property that represents the condition.
For example, let’s say you have a boolean data property named isChecked
that determines whether the radio button should be checked or not. You can bind the checked
attribute of the input element to this property using v-bind:checked="isChecked"
.
Then, whenever the value of isChecked
changes to true
, the radio button will be checked automatically. Similarly, when the value of isChecked
changes to false
, the radio button will be unchecked. This allows you to dynamically set the checked state of a radio button based on a condition in Vue.js.
How can you set a radio button as checked in Vue js if a certain condition is true?
In the code you provided, the :checked
attribute of the radio buttons is bound to a condition that checks whether condition
is equal to either true
or false
. If the condition is true, the radio button with the value of "true"
will be checked, and if it is false, the radio button with the value of "false"
will be checked.
In the mounted()
lifecycle hook, the initial value of selectedOption
is set to either "true"
or "false"
based on the value of condition
. This ensures that the correct radio button is checked when the component is first rendered.
When the user selects a different radio button, the selectedOption
data property is updated, which triggers the watch
function. The watch
function sets the value of condition
based on the new value of selectedOption
. This in turn updates the :checked
attribute of the radio buttons and ensures that the correct button is checked.
Overall, this code sets up a two-way binding between the selectedOption
and condition
data properties, so that changes to one property are reflected in the other. This ensures that the correct radio button is always checked based on the value of condition
Vue js set a radio button checked if statement is true Example
<div id="app">
<label>
<input type="radio" value="true" v-model="selectedOption" :checked="condition === true">
Option 1
</label>
<label>
<input type="radio" value="false" v-model="selectedOption" :checked="condition === false">
Option 2
</label>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
condition: true,
selectedOption: ''
}
},
mounted() {
this.selectedOption = this.condition ? 'true' : 'false';
},
watch: {
selectedOption(option) {
this.condition = option === 'true';
}
}
})
app.mount('#app')
</script>