vue3新特性 | <style> 中使用js变量

1.1 问题描述

  • 想要把从父组件传来的颜色,大小等样式属性应用到css中

1.2 代码片段

<template>
  <p>hello vue3</p>
</template>
<script setup lang="ts">
import { ref, toRefs } from "vue";
interface PropType {
	color?:string,
	fontSize?:string | number
}
const prop = withDefaultProps(defineProps<PropType>(),{
	color:'red',
	fontSize:18
})

1.3 解决方案

  • 使用vue3新特性 css v-bind
<template>
  <p>hello vue3</p>
</template>
<script setup lang="ts">
import { ref, toRefs } from "vue";
interface PropType {
	color?:string,
	fontSize?:string | number
}
const prop = withDefaultProps(defineProps<PropType>(),{
	color:'red',
	fontSize:18
})
const { color, fontSize } = toRefs(prop)

if(typeof(fontSize?.value) === 'number'){
	fontSize?.value = fontSize?.value + 'px'
}
</script>
<style scoped>
p {
  color: v-bind(color);
  font-size: v-bind(fontSize)
}
</style>

版权声明:本文为Mrbignose原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。