Preventing "class" attribute inheritance in VueJS props - tips and tricks

VueJS has the ability to automatically inherit Non-Prop Attributes, which is particularly useful for data-* attributes.

However, there are cases where we want to prevent inheriting the "class" and "style" attributes in order to protect our core components from layout changes that may be introduced by new developers. (We prefer all styling of a component to be contained within its style file)

Although using inheritAttrs: false can help avoid inheriting "non-prop attributes," it is important to note that this option does not affect class and style bindings.

https://v2.vuejs.org/v2/api/#inheritAttrs

Any suggestions on how to prevent "class" and "style" inheritance in core components?

Update:

A possible solution is:

<template>
 <div ref="root" class="hello">Hi</div>
</template>

<script>
export default {
  mounted() {
   this.$refs.root.className = 'hello'
  }
 }
</script>

However, this solution may become more complex when relying on a component's attributes:

Vue.component('my-feedback', {
        props: ['type'],
        data: function(){
            var vm = this;
            return {
                classes: {
                    'my-feedback-info': vm.type === 'info',
                    'my-feedback-note': vm.type === 'note',
                    'my-feedback-warning': vm.type === 'warning',
                    'my-feedback-success': vm.type === 'success'
                }
            };
        },
        template: `
                    <div class="my-feedback" :class="classes">
                        <slot></slot>
                    </div>
                `
    });

Update [20th May 2018]:

An answer was obtained through VueJS's Chat channel -

Solved JSFiddle - https://jsfiddle.net/53xuhamt/28/

Update [28th April 2021] 🎉

In Vue3, you can disable attribute inheritance with:

 inheritAttrs: false,

Vue3 Documentation - https://v3.vuejs.org/guide/component-attrs.html#disabling-attribute-inheritance

Example - https://jsfiddle.net/awan/oz5fbm2k/

Answer â„–1

Not the most elegant approach, but this method successfully solved my issue

data(){
   return {dynamicClass: ''}
},
mounted(){
   // Store the classes and apply them to specific nested elements
   this.dynamicClass = this.$el.classList.toString()

   // Clear the classes from the main element
   this.$el.setAttribute('class', '')
}

Answer â„–2

It is not possible to disable this feature, unless you are using a functional component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for avoiding asynchronous behavior in AJAX with JQuery

My questions are best explained through code rather than words. Take a look at the snippet below and try to understand it: $('#all').on('change', function(){ //ONCHANGE RADIOBUTTON, THERE ARE #bdo, #cash also. $.ajax({ type:"GET", ...

The responsiveness of Vuetify's v-data-table is compromised when utilizing the v-slot:body feature

Issue with Vuetify v-data-table not stacking on mobile devices when using the body v-slot Is there a way to make the data table stack properly even when it has the body v-slot implemented? The normal behavior of a v-data-table can be seen in the Vuetify d ...

Remove repeated selections in a dropdown menu using Vue JS

Could someone offer me some assistance, please? I have 3 dropdown menus that need to display specific subjects based on previous selections. One issue I'm facing is how to remove the initial selection in menu one from both menu two and menu three? I ...

Extract hidden form variables using a function in PHP

Here is the JavaScript function that I have written: function GetCellValues() { var rows = document.getElementsByTagName('tr'); var str = ''; for (var c = 1 ; c < rows.length ; c++) { str += '\n&apo ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

Exploring the Battery Manager functionality within AngularJS

I am attempting to connect the battery manager object to an Angular controller, but for some reason the controller object does not update when the promise provided by navigator.getBattery() is complete. Below is the code I have written: (function(){ var a ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Creating a Popup with JS, JQuery, CSS, and HTML

Seeking assistance in creating an HTML, CSS, and JS/jQuery popup. Looking to have a button that reveals a div tag when clicked, which can also be closed. Any quick responses with solutions would be greatly appreciated. Thank you in advance! ...

Tips for designing a personalized payment page in PayPal for flexible one-time and subscription-based payments

How can I display a PayPal checkout page with custom fields such as tax and total amount when a user makes a payment for a custom amount? Can multiple fields like sales tax and total amount be added? In addition to that, our web application already has Pa ...

Develop a fresh AngularJS directive that utilizes the HTML5 audio element

Recently delved into Angular and managed to create audio buttons using an Angular directive: app.directive('soundButton', [function () { return { restrict: 'E', link: function (scope, element, attrs) { v ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

"Utilizing Javascript's Regex to selectively replace only the first character

Forgive me if this is a beginner question, but I'm really unsure about this. Is there a regex solution to replace a character that appears first in a string? For example: 12 13 14 15 51 41 31 21 All data where '1' is the first character s ...

What are some methods to avoid redundant data across various windows?

In the process of developing an angular application, I have implemented a websocket for real-time updates transmission and reception. Within my application, users have the ability to open multiple windows that are launched from the main window, solely for ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

Unlock the secrets of programming with the must-have guide to mastering variables

As a newcomer to the world of programming, I may be jumping ahead by asking this question too quickly. While reading a book, I came across something that confused me. Why is it necessary to create a variable for the password box element? Wouldn't the ...

Using Vue.js to set a mobile browser's viewport height to 100%

My webpage has a min-height: 100vh property which causes some overflow on the bottom when rendered on mobile browsers. To fix this issue, I am using the following script: methods: { calcVH() { const vH = Math.max(document.documentElement.clien ...

Exploring the textures of an imported 3D model mesh with multiple materials in A-Frame and Three JS

Currently, I am exploring A-Frame using a 3D model imported from Blender. Some parts of this model contain multiple meshes with two or more materials assigned to them. It is easy for me to adjust the material properties of meshes with just one material. ...

What is the best way to send various variables using an onclick event?

My action plan was as follows: $(document).on("click", "#deleteMe", function (){ var id = $(this).data("id"); console.log(id); // the function responsible for deleting the event using its id belongs here }); The HTML for my delete button lo ...