vue如何在style标签中使用变量(数据)详解
参考资料
在 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属性呢?
也很简单
同样参考
<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标签使用变量内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
基于vue-cli、elementUI的Vue超简单入门小例子(推荐)
这篇文章主要介绍了基于vue-cli、elementUI的Vue超简单入门小例子,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04
vue3响应式Proxy与Reflect的理解及基本使用实例详解
这篇文章主要为大家介绍了vue3响应式Proxy与Reflect的理解及基本使用实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-08-08
antd-DatePicker组件获取时间值,及相关设置方式
这篇文章主要介绍了antd-DatePicker组件获取时间值,及相关设置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10


最新评论