VueJS 自动继承 Non-Prop Attributes ,它非常适合 data-* 属性。
但我们不想继承“class”和“style”属性来保护我们的核心组件免受任何新开发人员的任何布局更改。(因为我们希望组件的所有样式都包含在它的样式文件中)
有 inheritAttrs: false
来避免“非 prop 属性”继承,但是:
Note: this option does not affect class and style bindings.
https://v2.vuejs.org/v2/api/#inheritAttrs
那么建议避免核心组件中的“类”和“样式”继承?
更新:
建议的解决方案:
<template>
<div ref="root" class="hello">Hi</div>
</template>
<script>
export default {
mounted() {
this.$refs.root.className = 'hello'
}
}
</script>
但是当依赖于组件的属性时,建议的解决方案甚至会变得复杂:
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>
`
});
更新 [2018 年 5 月 20 日]:
通过 VueJS 的聊天 channel 得到答案 - https://discordapp.com/channels/325477692906536972/325479107012067328
已解决 JSFiddle - https://jsfiddle.net/53xuhamt/28/
更新 [2021 年 4 月 28 日] 🎉
在 Vue3 中,我们可以通过以下方式禁用属性继承:
inheritAttrs: false,
Vue3 文档 - https://v3.vuejs.org/guide/component-attrs.html#disabling-attribute-inheritance
最佳答案
非常棘手的解决方案,但这对我有用
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', '')
}
关于javascript - VueJS Prop - 如何避免 "class"属性继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304399/