[Vuejs]-VueJS v3: automatically add css class to any component

0👍

I managed to get it to work… 🙂

My plugin registers a function that gets triggered on Browser window resize. So in the event handler method I utilize the following bit of code:

// this.breakpoints is a key/value object containing breakpoint names and their respective width values
let cssClasses = this.$el.className;
if (typeof cssClasses !== "string") {
  cssClasses = "";
}
cssClasses = cssClasses.split(" ");
cssClasses = cssClasses.filter(elem => Object.keys(this.breakpoints).indexOf(elem.replace(/^bootstrap\-/, '')) === -1);
cssClasses.push("bootstrap-" + this.currentBootstrapBreakpoint);
try {
  this.$el.className = cssClasses.join(" ").trim();
} catch (e) {}

Since this plugin gets applied automatically to all components, there might be DOM node types that don’t feature the use of CSS classes or provide setters for them (e.g. SVG nodes), hence the additional checks and precautions not to trigger javascript errors.

Leave a comment