【问题标题】:How can I apply css to the child tag from component如何将 css 应用于组件中的子标签
【发布时间】:2022-07-07 07:10:21
【问题描述】:

<ButtonAtom></ButtonAtom>

这是我制作的按钮组件。

<template>
 <div>
  <button class="px-2 py-1" :class="[borderRadius, backgroundColor]">
    <slot />
  </button>
 <div>
</template>

这是组件内的html标签。

如果我将 css 添加到 &lt;ButtonAtom&gt;,例如 &lt;ButtonAtom color="white"&gt;

颜色连接到根标签&lt;div&gt;

关键是如果我尝试将 css 连接到 &lt;button&gt;。

有什么方法可以在不删除根html&lt;div&gt;的情况下连接&lt;button&gt;

P.S 这是 vue3。

【问题讨论】:

  • 属性 color="white" 不是 css - 如果你想拥有一个名为 color 的属性 - 使用 props

标签: javascript html css typescript vue.js


【解决方案1】:

您应该将带有color:white 的样式属性作为属性&lt;ButtonAtom style="color:white"&gt; 传递,然后在子组件中添加inheritAttrs:false 并将$attrs 绑定到按钮元素:

<template>
 <div>
  <button class="px-2 py-1" v-bind="$attrs" :class="[borderRadius, backgroundColor]">
    <slot />
  </button>
 <div>
</template>
<script>
export default {
  inheritAttrs: false
}
</script>


【讨论】:

    【解决方案2】:

    只是一个较短的示例,但您是否已经尝试过:

    <button style="color: white"></button>
    

    【讨论】:

    • 这将硬编码组件内按钮的颜色 - 这不是 OP 想要的
    • 他们想要传递在&lt;button&gt; 上使用的属性,出于某种原因,他们认为&lt;div&gt; 的存在阻止了他们这样做,因为他们认为&lt;div&gt; 会得到color 属性。但是,只有 class 和 style 以及任何未在组件中声明为 props 的属性会以这种方式运行——这就是我建议他们使用 props 的原因。希望能弄清楚为什么您的答案没有解决问题的任何方面。 OP 还有东西color="white" 在某种程度上是 CSS
    【解决方案3】:

    您可以将颜色作为道具传递给按钮组件并在按钮本身上使用它

          <template>
         <div>
          <button class="px-2 py-1" v-bind="$attrs" :class="[borderRadius, backgroundColor]">
            <slot />
          </button>
         <div>
        </template>
        <script>
        export default {
          props: {
        color: String,
      }
        }
        </script>
    

    并在父组件中使用它

    <ButtonAtom color="white">
    

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 2022-11-16
      • 2019-06-22
      • 1970-01-01
      • 2018-01-26
      • 2017-03-02
      相关资源
      最近更新 更多