Vue3基础(十ba)___在css中使用props或者计算属性的变量,来实现动态样式

简介: 本文介绍了如何在Vue3中通过CSS变量和props或计算属性来实现动态样式。

主要使用到了css3中var

<template >
  <div class="container">
    <p
      class="p1"
      :style="{'--width':width,'--height':height,'--background':bgc,...objStyle}"
    >obj2====={
   {
   obj2}}</p>
  </div>
</template>
<script>
import {
    ref, computed } from "vue";
export default {
   
  props: {
   
    width: {
    type: String, default: "300px" }, // 宽度
    height: {
    type: String, default: "100px" }, // 高度
    bgc: {
    type: String, default: "#ccc" } //北京颜色
  },
  setup(p, {
    emit }) {
   
    const obj = ref({
    obj1: "obj111", obj2: "obj222", obj3: "obj333" });
    let objStyle = computed(() => {
   
      return {
    "--fontSize": "22px" };
    });
    return {
    ...obj.value, objStyle};
  }
};
</script>
<style  scoped>
.p1 {
   
  width: var(--width);
  height: var(--height);
  background-color: var(--background);
  color: var(--main-bg-color);
  font-size: var(--fontSize);
}
.container {
   
  color: var(--main-bg-color);
  font-size: var(--main-padding);
}
</style>

1:
通过props接受变量:然后在页面上使用:只有传入style中才能使用,核心代码:

  props: {
   
    width: {
    type: String, default: "300px" }, // 宽度
    height: {
    type: String, default: "100px" }, // 高度
    bgc: {
    type: String, default: "#ccc" } //北京颜色
  },

 <p class="p1"
    :style="{'--width':width,'--height':height,'--background':bgc,...objStyle}"
    ></p>

CSS:
.p1 {
   
  width: var(--width);
  height: var(--height);
  background-color: var(--background);
  color: var(--main-bg-color);
}

2:使用computed计算属性,核心代码:
我们可以直接使用computed中返回的对象 --fontSize ==》 22px

let objStyle = computed(() => {
   
      return {
    "--fontSize": "22px" };
    });
.p1 {
   
  font-size: var(--fontSize);
}
目录
相关文章
|
4月前
|
前端开发 JavaScript
vue 动态改变css样式
vue 动态改变css样式
114 0
|
11月前
|
前端开发 JavaScript
25Vue - 绑定内联样式(数组、自动添加前缀)
25Vue - 绑定内联样式(数组、自动添加前缀)
47 0
|
19天前
|
JavaScript API
Vue3中的计算属性能否动态修改
【9月更文挑战第5天】Vue3中的计算属性能否动态修改
64 10
Vue3使用element-plus图标,局部引入写法
Vue3使用element-plus图标,局部引入写法
|
4月前
|
JavaScript 前端开发 UED
Vue class和style绑定:动态美化你的组件
Vue class和style绑定:动态美化你的组件
|
9月前
|
前端开发
在vue2的style标签中使用css变量
在vue2的style标签中使用css变量
174 0
|
11月前
|
前端开发 JavaScript
24Vue - 绑定内联样式(对象语法)
24Vue - 绑定内联样式(对象语法)
44 0
|
JavaScript
Vue中避免样式冲突 scoped 属性的方法
Vue中避免样式冲突 scoped 属性的方法
|
前端开发 小程序
UniApp 解决 style 绑定 css 变量,支持 var() 使用
UniApp 解决 style 绑定 css 变量,支持 var() 使用
2053 0
|
JavaScript 前端开发
Vue —— 基础(三)(样式绑定、条件渲染)
Vue —— 基础(三)(样式绑定、条件渲染)
105 1