Vue Checkbox Checked Event: In Vue.js, the “checked” event is triggered when a checkbox input element changes its checked state. This event can be used to perform some action or update the state of the component or application. The “change” event is similar, but it is triggered whenever the input element’s value changes, not just when the “checked” state changes. Therefore, it can be used for a wider range of input types, such as text inputs or radio buttons. In both cases, event handling in Vue.js is done using v-on directives and event handler functions defined in the component’s methods or computed propertie.
How can I detect when a Vue checkbox is checked or unchecked and perform an action accordingly?
This is a Vue.js code snippet that defines a component with a checkbox and a message that changes depending on whether the checkbox is checked or unchecked.
The isChecked
variable is initially set to false
. The v-model
directive binds the value of the checkbox to the isChecked
variable.
The @change
event handler is triggered when the checkbox is clicked. The handleCheckedChange
method checks the value of isChecked
and sets the result
variable accordingly. If the checkbox is checked, the message “Checkbox is checked!” is displayed. Otherwise, the message “Checkbox is unchecked!” is displayed.
The Pre
component is used to display the result
message when it is not empty.
Overall, this code demonstrates how to detect changes to a checkbox in Vue.js and perform actions based on its checked state.
Vue Checkbox Checked Event Example
<div id="app">
<label>
<input type="checkbox" v-model="isChecked" @change="handleCheckedChange">
Checkbox Label
</label>
<Pre v-if="result">Output: {{result}}</Pre>
</div>
<script>
const app = Vue.createApp({
data() {
return {
isChecked: false,
result: ''
};
},
methods: {
handleCheckedChange() {
// Get the current value of the checkbox
const isChecked = this.isChecked;
// Do something based on the value of the checkbox
if (isChecked) {
this.result = 'Checkbox is checked!';
// ... do something else when the checkbox is checked ...
} else {
this.result = 'Checkbox is unchecked!';
// ... do something else when the checkbox is unchecked ...
}
}
}
});
app.mount('#app');
</script>