vue在style标签使用变量

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue在style标签使用变量

Z_ One Dream   2022-09-29 我要评论

参考资料

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

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们