3

VueJS はNon-Prop Attributesを自動継承します。これは data-* 属性に最適です。

しかし、新しい開発者によるレイアウトの変更からコアコンポーネントを保存するために、「クラス」と「スタイル」の属性を継承したくありません (スタイルファイル内のコンポーネントのすべてのスタイリングが必要なため)。

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 Doc - https://v3.vuejs.org/guide/component-attrs.html#disabling-attribute-inheritance

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

4

2 に答える 2

4

かなりハッキーなソリューションですが、これは私にとってはうまくいきました

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 に答える