Awan
Awan

Reputation: 159

VueJS props - How can i avoid "class" attribute inheritance?

VueJS auto inherit Non-Prop Attributes, it's great for data-* attributes.

But we don't want to inherit "class" & "style" attributes to save our core-components from any layout change by any new developer.(Because we want all styling of component within it's style file)

There is inheritAttrs: false to avoid "non-prop attribute" inheritance but:

Note: this option does not affect class and style bindings.

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

So suggestions to avoid "class" & "style" inheritance in core component?

Update:

Suggested solution:

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

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

But suggested solution even complicated when depend on 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]:

Got answer via VueJS's Chat channel - https://discordapp.com/channels/325477692906536972/325479107012067328

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

Update [28th April 2021] 🎉

In Vue3, we could disable attribute inheritance via:

 inheritAttrs: false,

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

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

Upvotes: 4

Views: 5904

Answers (2)

danielkelly_io
danielkelly_io

Reputation: 61

Pretty hacky solution but this worked for me

data(){
   return {staticClass: ''}
},
mounted(){
   // Capture the classes and use them on nested elements where desired
   this.staticClass = this.$el.classList.toString()

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

Upvotes: 4

Decade Moon
Decade Moon

Reputation: 34306

You can't opt out of this behavior, unless it's a functional component.

Upvotes: 0

Related Questions