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/