In Vue, you can toggle the visibility of elements or components using various approaches. Here are some common ways to do so:
1. Using v-show directive
The v-show directive can be used to toggle the visibility of elements by changing their CSS display property. This approach is more efficient than using v-if for frequent toggling because the element is not destroyed and recreated:
app.component('VShowDirective', {
data: () => ({ toggle: true }),
template: `
<div>
<div class="alert alert-danger" role="alert" v-show="toggle">
A simple danger alert—check it out!
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="toggleSwitch-1" v-model="toggle" />
<label class="form-check-label" for="toggleSwitch-1">Show danger message</label>
</div>
</div>
`
});
2. Using v-if directive
You can use the v-if and v-else directives to conditionally render elements or components based on a specific condition. For example:
app.component('VIfDirective', {
data: () => ({ toggle: true }),
template: `
<div>
<div class="alert alert-warning" role="alert" v-if="toggle">
A simple warning alert—check it out!
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="toggleSwitch-2" v-model="toggle" />
<label class="form-check-label" for="toggleSwitch-2">Show warning message</label>
</div>
</div>
`
});
3. Using v-bind:class
You can use CSS classes to toggle visibility by adding or removing specific classes based on your condition. For example:
app.component('VBindClass', {
data: () => ({ toggle: true }),
template: `
<div>
<div class="alert alert-success" role="alert" v-bind:class="{ 'd-none': !toggle }">
A simple success alert—check it out!
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="toggleSwitch-3" v-model="toggle" />
<label class="form-check-label" for="toggleSwitch-3">Show success message</label>
</div>
</div>
`
});
Demo
See the Pen Untitled by Stanescu Eduard-Dan (@ZsharE) on CodePen.