在小程序的開發中,有時候須要根據 page 的 data 中的數據來決定頁面中的某元素加不加載,或者一個元素有沒有某個屬性,這時候就能夠用三元運算符來實現。小程序
如今有這樣一個需求: 在 page 的 data 中定義一個變量 portrait 來表示屏幕是橫屏仍是豎屏,若是是豎屏則 portrait 爲 true,若是是橫屏則 portrait 爲 false。若是 portrait 爲 true,則 view 的 class 爲 portrait-container,若是 portrait 爲 false,則 view 的 class 爲 landscape-container。這時候就能夠用三元運算符來寫:code
<view class="{{portrait?'portrait-container':'landscape-container'}}"></view>
注意,portrait-container 和 landscape-container 必須用單引號引發來,否則最終的 class 會變成 NaN。開發