当某个组件的样式需要根据传入的变量进行动态变化,如果给组件设置不同的class样式进行切换,会比较繁琐,此时建议采用计算属性的方式。
通过计算属性进行样式的计算得到返回值之后,将返回值赋值给对应的组件style,就能够做到样式的动态变化。
完整实现代码如下:
-
- <div style="width: 100%">
-
-
- <text style="{{textStyle}}">我是显示的文字text>
-
- div>
-
-
- <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/forum/?ha_source=zzh