首页 > 解决方案 > 如何将 vue 组件上的类和样式属性传递给 $attrs 等不同的元素?

问题描述

我有一个名为的文件组件confirm-document,看起来像这样:

沙盒

<template>
  <v-dialog>
    <template v-slot:activator="{ on }">
      <v-btn v-bind="$attrs" :class="activatorClass" v-on="on">{{
        title
      }}</v-btn>
    </template>
    <v-card>
      <v-card-title>{{ title }}</v-card-title>
      <v-card-text><slot></slot></v-card-text>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: "ConfirmDocument",
  props: {
    title: String,
    activatorClass: {},
  },
};
</script>

所以当我然后使用这个组件时:

<ConfirmDocument
    class="useless-class"
    activator-class="mt-4 ml-n4"
    title="Consent"
> Document Content </ConfirmDocument>

沙盒

这些类被应用到v-dialog,它最终成为一个不可见的 div,里面没有任何内容,并且激活器和模态都作为兄弟节点附加。

由于这主要是一个提供一致 UI 的包装器组件,因此我实际上只需要激活器是可定位的。所以我想将类和样式道具传递给 v-activator。

我宣布的activator-class道具实际上工作正常。但是我很好奇是否有办法改变组件的类和样式属性所绑定的元素,以便我可以使用类来代替?

标签: cssvue.jsvue-component

解决方案


我认为您可以使用该inheritAttrs: false物业。它的作用是确保属性不会自动应用于根元素,并且它允许您选择在何处应用它们。

<template>
  <v-dialog>
    <template v-slot:activator="{ on }">
      <v-btn v-bind="buttonAttrs" >Read {{ title }}</v-btn>
    </template>
    <v-card>
      <slot></slot>
    </v-card>
  </v-dialog>
</template> 

<script>
export default {
  inheritAttrs: false,
  props: {
    title: {type: String},
  },
  computed: {
    buttonAttrs () {
      // select which attrs to apply
      const { title, ...rest } = this.$attrs;

      return rest;
    }
  }
}
</script>

可以在此处找到一个工作(并且有点混乱)的示例。


推荐阅读