You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何在CSS中获取data属性的值?

在Vue中如何在CSS里获取data属性的值?

嘿,这个问题我之前踩过坑!咱们先搞清楚为什么你的代码会报错,再给你几个可行的解决方案~

为什么直接用attr()不行?

CSS的attr()函数目前仅在伪元素的content属性上有完善的浏览器支持,像background这类样式属性,主流浏览器还没实现对它的支持,所以你直接写background: attr(data-background)肯定会报错。

解决方案

方案1:使用内联样式(最简单直接)

直接在Vue模板里通过:style绑定背景色,这种方式适合简单场景:

<template>
  <!-- 直接读取data属性的值 -->
  <p :style="{ background: $attrs['data-background'] }"> TEST </p>
  
  <!-- 或者提前定义变量,更易维护 -->
  <!-- <p :style="{ background: bgColor }" data-background="purple"> TEST </p> -->
</template>

<script setup>
// 如果用变量的话,这里可以定义或者从props获取
// const bgColor = 'purple';
</script>

方案2:CSS变量(推荐,适合复杂样式场景)

通过Vue绑定CSS变量,把data属性的值同步到CSS变量中,然后在<style>里引用这个变量——不管是元素本身还是伪元素都能正常使用:

<template>
  <p 
    data-background="purple"
    :style="{'--bg-color': $attrs['data-background']}"
  > 
    TEST 
  </p>
</template>

<style lang="scss">
p {
  background: var(--bg-color);
  
  &:after {
    content: '';
    display: block;
    width: 100%;
    height: 15px;
    background: var(--bg-color); // 伪元素也能正常引用变量
  }
}
</style>

方案3:动态data属性场景(比如从props传值)

如果你的data属性是动态的(比如从父组件传过来的),可以把变量同时绑定到data属性和CSS变量上:

<template>
  <p 
    :data-background="bgColor"
    :style="{'--bg-color': bgColor}"
  > 
    TEST 
  </p>
</template>

<script setup>
import { defineProps } from 'vue';
// 从父组件接收背景色参数
const props = defineProps({
  bgColor: {
    type: String,
    default: 'purple'
  }
});
</script>

<style lang="scss">
p {
  background: var(--bg-color);
  
  &:after {
    background: var(--bg-color);
  }
}
</style>

总结

如果样式逻辑简单,内联样式足够用;如果需要在<style>里管理复杂样式(包括伪元素),CSS变量是最优解,它能完美衔接Vue的动态数据和CSS样式。

内容的提问来源于stack exchange,提问作者Knight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:30:05