Blog>
Snippets

Vue.js Content Placeholder Plugin

Create a plugin that offers a content placeholder directive to show loading placeholders for asynchronous content like text, images, or cards.
Vue.directive('content-placeholder', {
  bind(el, binding) {
    el.classList.add('placeholder');
    el.setAttribute('data-placeholder', binding.value);
  },
  update(el, binding) {
    if (!binding.value) {
      el.classList.remove('placeholder');
    }
  }
});
Defines a Vue.js directive 'content-placeholder' that can be added to elements needing a placeholder during loading. It adds a class and a data attribute, and removes them once content is loaded.
.placeholder {
  background-color: #e0e0e0;
  border-radius: 4px;
  min-height: 20px;
  margin: 4px 0;
}
.placeholder[data-placeholder="text"] {
  width: 100%;
  height: 20px;
}
.placeholder[data-placeholder="image"] {
  width: 100px;
  height: 100px;
}
.placeholder[data-placeholder="card"] {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  height: 200px;
}
CSS styles for the placeholder. It includes general styles for all placeholders and additional styles based on the data-placeholder attribute's value.
<div v-content-placeholder="'text'">{{ asyncTextContent }}</div>
<img v-content-placeholder="'image'" :src="asyncImageSrc" />
<div v-content-placeholder="'card'">
  <!-- card content -->
</div>
HTML demonstrating how to use the 'v-content-placeholder' directive on different elements to show placeholders for text, images, or cards.