如何将 vue 组件上的类和样式属性传递给不同的元素(例如 $attrs)?

Kaa*_*aan 4 css vue.js vue-component

我有一个名为的单个文件组件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>
Run Code Online (Sandbox Code Playgroud)

所以当我像这样使用这个组件时:

<ConfirmDocument
    class="useless-class"
    activator-class="mt-4 ml-n4"
    title="Consent"
> Document Content </ConfirmDocument>
Run Code Online (Sandbox Code Playgroud)

沙盒

这些类被应用到v-dialog,最终成为一个不可见的 div,里面什么都没有,并且激活器和模态都作为同级节点附加。

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

activator-class我所声明的道具实际上效果很好。但我很好奇是否有一种方法可以更改组件的类和样式属性绑定到的元素,以便我可以使用类来代替?

Mom*_*hid 6

这已在 Vue.js v3 参考中修复

对于 Vue.js v2,你可以尝试这个

检查v-bindattrs计算下面的属性

<template>
  <v-dialog>
    <template v-slot:activator="{ on }">
      <v-btn v-bind="attrs" 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",
  inheritAttrs: false, // <- added just for safety
  props: {
    title: String,
  },
  computed: {
    attrs() {
      const attrs = { ...self.$attrs }

      // adding class and style for `v-bind`
      attrs.class = self.$vnode.data.staticClass
      attrs.style = self.$vnode.data.staticStyle
            
      return attrs
    }
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)

说明 -在 Vue.js 版本 2.xx 中,$attrs不包含classand style参考),但在很多情况下,我们希望将所有 props 以及类和样式传递到另一个组件中,因此,$attrs应该有classand ,style其中它们确实在 vue.js 版本 3 中添加了。github上有关于这个主题的详细讨论,请查看以获取更多详细信息。

对于版本2,我们想要实现的是类和样式可以传递给另一个组件。我们可以通过从当前组件节点获取类[作为字符串]和样式[作为对象]来vnode实现它,然后使用v-bind.

ConfirmDocument现在,您可以直接从父(或调用者)组件将 props 以及类和样式传递到另一个组件中