3

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

示例 - https://jsfiddle.net/awan/oz5fbm2k/

4

2 回答 2

4

非常hacky的解决方案,但这对我有用

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', '')
}
于 2019-08-27T19:13:01.610 回答
0

您不能选择退出此行为,除非它是功能组件。

于 2018-05-12T08:55:49.300 回答