VueJS 自动继承Non-Prop 属性,非常适合 data-* 属性。
但是我们不想继承“class”和“style”属性来保存我们的核心组件免受任何新开发人员的任何布局更改。(因为我们希望组件的所有样式都在它的样式文件中)
有inheritAttrs: false
避免“非道具属性”继承,但:
注意:此选项不影响类和样式绑定。
https://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 的聊天频道得到答案 - 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