Blog>
Snippets

Color Binding Directive

Build a custom directive that binds an element's background color to a color value provided in the directive's argument.
Vue.directive('bind-color', {
  bind(el, binding) {
    el.style.backgroundColor = binding.value;
  },
  update(el, binding) {
    el.style.backgroundColor = binding.value;
  }
});
This code defines a Vue.js custom directive called 'bind-color'. The directive has two hooks: 'bind' and 'update'. The 'bind' hook applies a background color to the element when the directive is first bound to the element. The color is taken from the directive's argument (binding.value). The 'update' hook applies a new background color to the element whenever the value of the directive's argument changes.