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

参考资料

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');

猜你喜欢

转载自blog.csdn.net/weixin_42335036/article/details/125561798
今日推荐