Blog>
Snippets

Conditional Display Directive

Implement a custom directive that toggles the visibility of an element based on a condition passed via directive's binding value.
Vue.directive('conditional-display', {
  bind(el, binding) {
    // Initial hiding or showing based on the binding value
    el.style.display = binding.value ? '' : 'none';
  },
  update(el, binding) {
    // Respond to changes in the binding value
    el.style.display = binding.value ? '' : 'none';
  }
});
Defines a custom Vue directive called 'conditional-display' that toggles the display property of an element. The element is initially shown or hidden based on the passed binding's value, and it updates as the value changes.
// Usage example in a Vue component template
// <div v-conditional-display="shouldDisplay">This will be conditionally displayed</div>
Shows how to use the 'conditional-display' directive in a Vue component template. The 'shouldDisplay' property controls the visibility of the div element.