css - 如何将 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
道具实际上工作正常。但是我很好奇是否有办法改变组件的类和样式属性所绑定的元素,以便我可以使用类来代替?
解决方案
我认为您可以使用该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>
可以在此处找到一个工作(并且有点混乱)的示例。
推荐阅读
- c++ - 将“this”传递给 C API 回调,获取 void* 用户数据
- javascript - Discord Bot:在重新加载时不会重置的每个公会变量
- javascript - 将赛季时间表分成几周而不重复球队比赛
- ruby-on-rails - 如何在rails中创建word文档
- python - 将 PDF 文件转换为 HTML 的最佳方法
- android - 如何在类方法中执行 Room 请求?
- java - 使用按钮更改jsp中的变量值
- excel - 从 DataGridView 获取数据(数据取自 excel)并在 vb.net 图表上显示
- javascript - 如何使用 img.src 构造渲染函数
- javascript - 如何根据随机播放的视频在 html 中显示文本?