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/
mounted() { this.$el.className = 'only classes you want'; }classandstyleattributes from a component's root element, that won't prevent styles from cascading into the component from parents. Just define all the style rules that you don't want overridden in the component and make sure that new developers don't use!important