发布于 3年前

小程序开发之WXML中的三元运算符

在小程序的开发中,有时候需要根据 page 的 data 中的数据来决定页面中的某元素加不加载,或者一个元素有没有某个属性,这时候就可以用三元运算符来实现。

现在有这样一个需求: 在 page 的 data 中定义一个变量 portrait 来表示屏幕是横屏还是竖屏,如果是竖屏则 portrait 为 true,如果是横屏则 portrait 为 false。如果 portrait 为 true,则 view 的 class 为 portrait-container,如果 portrait 为 false,则 view 的 class 为 landscape-container。这时候就可以用三元运算符来写:

<view class="{{portrait?'portrait-container':'landscape-container'}}"></view>

注意,portrait-container 和 landscape-container 必须用单引号引起来,不然最终的 class 会变成 NaN。

©2020 edoou.com   京ICP备16001874号-3