目录在 style 中使用 data 变量那么如何在代码中使用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 方式大同小异
==========================================================================================
也很简单
同样参考
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');
到此这篇关于vue如何在style标签中使用变量(数据)的文章就介绍到这了,更多相关vue在style标签使用变量内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: vue如何在style标签中使用变量(数据)详解
本文链接: https://www.lsjlt.com/news/168047.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0