找回密码
 立即注册
搜索

如何通过计算属性控制组件样式

1
回复
382
查看
[复制链接]

46

主题

47

帖子

465

积分

 楼主| 2021-9-3 11:01:42 显示全部楼层 |阅读模式

需求描述

当某个组件的样式需要根据传入的变量进行动态设置,这时如果采用给组件设置不同的class样式进行切换,会比较繁琐,有什么好的办法么?

回复

使用道具 举报

23

主题

142

帖子

825

积分

2021-9-3 11:03:58 显示全部楼层

需求分析

一般我们建议采用计算属性的方式,通过计算属性的方式进行样式的计算得到返回值之后,将返回值赋值给对应的组件style,就能够做到样式的动态变化。

 

组件样式的设置:

<text style="{{textStyle}}">我是显示的文字</text>

 

计算属性返回样式结果:

    computed: {

      textStyle() {

        var style = '';

        style += 'width:' + this.width + 'px;'

        style += 'height:' + this.height + 'px;'

        style += 'font-size:' + this.size + 'px;'

        style += 'backgroundColor:' + this.backgroundColor + ';'

        return style;

      }

    }

解决方法

完整代码:

<template>

  <div style="width: 100%">

    <text style="{{textStyle}}">我是显示的文字</text>

  </div>

</template>

 

<script>

  export default {

    data: {

      width: 300,

      height: 100,

      size: 40,

      backgroundColor: '#dc143c'

    },

    computed: {

      textStyle() {

        var style = '';

        style += 'width:' + this.width + 'px;'

        style += 'height:' + this.height + 'px;'

        style += 'font-size:' + this.size + 'px;'

        style += 'backgroundColor:' + this.backgroundColor + ';'

        return style;

      }

    }

  };

</script>

 

<style>

</style>

 

欲了解更多详情,请参见:

计算属性介绍:

https://developer.huawei.com/consumer/cn/doc/development/quickApp-Guides/quickapp-topic-computed-0000001112756396


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册