uni-app 小程序标签上绑定style 对象变量无效

uni-app 小程序标签上绑定style 对象变量无效

示例代码:

微信小程序标签上绑定style 对象变量无效 节点渲染后是[object Object] h5正常

操作步骤:

微信小程序标签上绑定style 对象变量

预期结果:

和h5一样正常给style值

实际结果:

style渲染后是[object Object]

bug描述:

信息类型 内容
产品分类 uniapp/小程序/微信
PC开发环境操作系统 Windows
PC开发环境操作系统版本号 windows10
第三方开发者工具版本号 1.05.2107221
基础库版本号 2.19.2
项目创建方式 CLI
CLI版本号 ^2.0.0-31920210709003

https://www.itying.com/uniimg.php?url=https://img-cdn-tc.dcloud.net.cn/uploads/questions/20210820/21317a140616735e8a487c71fa6d73ee.png

https://www.itying.com/uniimg.php?url=https://img-cdn-tc.dcloud.net.cn/uploads/questions/20210820/75e0a6f554089872eaa65dbce2af40fb.png


更多关于uni-app 小程序标签上绑定style 对象变量无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

:style="[对象变量]" 实测微信小程序可以

更多关于uni-app 小程序标签上绑定style 对象变量无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


感谢大佬,亲测有效!

直接在标签上写对象可以,在data中申明对象再使用就不行

收到

这是微信小程序和H5平台在样式绑定上的差异导致的。微信小程序原生不支持直接绑定style对象,而H5可以。

解决方案:

  1. 使用计算属性将对象转为字符串(推荐):
computed: {
  styleStr() {
    const obj = { color: 'red', fontSize: '16px' }
    return Object.entries(obj)
      .map(([key, value]) => `${key}:${value}`)
      .join(';')
  }
}
  1. 使用模板字符串直接拼接
<view :style="`color:${color};font-size:${fontSize}`"></view>
  1. 使用uniapp的rpx单位转换函数(如果需要单位转换):
import { upx2px } from '@/uni_modules/uni-scss'
回到顶部