vue 如何在 style 标签里使用变量(数据)

18 篇文章 3 订阅

参考资料

SFC CSS Features | Vue.js

在 style 中使用 data 变量

options 方式:

<template>
  <div class="text">hello</div>
</template>

<script>
export default {
  data() {
    return {
      color: 'red'
    }
  }
}
</script>

<style>
.text {
  color: v-bind(color);
}
</style>

Composition 方式

<script setup>
const theme = {
  color: 'red'
}
</script>

<template>
  <p>hello</p>
</template>

<style scoped>
p {
  color: v-bind('theme.color');
}
</style>

还有一个问题,如果我们的变量是数字,但是我们想要设置像素怎么办?

其实这个很好解决

一种是使用 computed 计算属性改变它

<script setup>
import { computed } from 'vue';
const props = defineProps({ size: Number });

const sizePx = computed(() => `${props.size}px`)
</script>

<template>
  <p>hello</p>
</template>

<style scoped>
p {
  font-size: v-bind(sizePx);
}
</style>

还有一种方式是使用 calc css 计算属性

<script setup>
defineProps({ size: Number });
</script>

<template>
  <p>hello</p>
</template>

<style scoped>
p {
  font-size: calc(1px * v-bind(size));
}
</style>

当然还有第三种那就是传值的时候就传成字符串格式

option 方式大同小异

==========================================================================================

那么如何在代码中使用style属性呢?

也很简单

同样参考

SFC CSS Features | Vue.js

<template>
  <p :class="$style.red">This should be red</p>
</template>

<style module>
.red {
  color: red;
}
</style>

还可以设置不同的变量

<template>
  <p :class="classes1.red">This should be red</p>
</template>

<style module="classes1">
.red {
  color: red;
}
</style>

<style module="classes2">
.red {
  color: green;
}
</style>

如果是在 script 中使用,可以使用 useCssModule

import { useCssModule } from 'vue';

const classes1 = useCssModule('classes1');

const classes2 = useCssModule('classes2');

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值