javascript - VueJS Prop - 如何避免 "class"属性继承?

标签 javascript vue.js vuejs2 vue-component vuejs3

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

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

最佳答案

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

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/

相关文章:

javascript - 使用 jQuery 更改 css 样式(在容器内)

javascript - 堆叠条形图上的单击事件 - ChartJs

javascript - 在 Angular 中使用 BehaviourSubject 在两个组件之间进行通信

javascript - 具有基于数组值的 3 向切换功能的 Vue 按钮

docker - docker 文件中的 VueJS 变量

javascript - Vuex 状态数组键

javascript - 在Vue js组件中渲染时如何制作动态v-if?

javascript - 用于聊天应用程序或私有(private)应用程序的 Firebase 数据结构

Javascript 无法正确排序包含两个数组值的数组

javascript - 独特的数据 v-model vue