加载中...

1.2.4 显示逻辑控制器


Weex前端语义支持通过两种特殊属性(if和repeat)的设置来确定组件的显示状态,这会使得整个页面布局显得更加灵活。

if

通过设置if属性值,可以控制当前组件节点的显示状态。如果设为true,则会将当前节点置于DOM中渲染,反之则会从DOM中移除。

  1. <template>
  2. <container>
  3. <text onclick="toggle">Toggle</text>
  4. <image src="..." if="{{shown}}"></image>
  5. </container>
  6. </template>
  7.  
  8. <script>
  9. module.exports = {
  10. data: {
  11. shown: true
  12. },
  13. methods: {
  14. toggle: function () {
  15. this.shown = !this.shown
  16. }
  17. }
  18. }
  19. </script>

repeat

repeat属性用于控制具有相同样式或属性的组件节点做重复渲染。它绑定的数据类型必须为数组,其中每个数组项的属性会分别绑定到需要重复渲染的各子组件上。

  1. <template>
  2. <container>
  3. <container repeat="{{list}}" class="{{gender}}">
  4. <image src="{{avatar}}"></image>
  5. <text>{{nickname}}</text>
  6. </container>
  7. </container>
  8. </template>
  9.  
  10. <style>
  11. .male {...}
  12. .female {...}
  13. </style>
  14.  
  15. <script>
  16. module.exports = {
  17. data: {
  18. list: [
  19. {gender: 'male', nickname: 'Li Lei', avatar: '...'},
  20. {gender: 'female', nickname: 'Han Meimei', avatar: '...'},
  21. ...
  22. ]
  23. }
  24. }
  25. </script>

此外,weex同样支持不在repeat数组中的数据绑定到重复渲染的组件节点上。

  1. <template>
  2. <container>
  3. <container repeat="{{list}}" class="{{gender}}">
  4. <image src="{{avatar}}"></image>
  5. <text>{{nickname}} - {{group}}</text>
  6. </container>
  7. </container>
  8. </template>
  9.  
  10. <style>
  11. .male {...}
  12. .female {...}
  13. </style>
  14.  
  15. <script>
  16. module.exports = {
  17. data: {
  18. group: '...',
  19. list: [
  20. {gender: 'male', nickname: 'Li Lei', avatar: '...'},
  21. {gender: 'female', nickname: 'Han Meimei', avatar: '...'},
  22. ...
  23. ]
  24. }
  25. }
  26. </script>

repeat属性扩展

使用 $index 获取当前节点所绑定的数据在repeat数组中的索引值.

例如:

  1. <div repeat="{{list}}">
  2. <text>No. {{$index + 1}}</text>
  3. <div>

获取repeat数组的属性值.

例如:

  1. <div repeat="{{v in list}}">
  2. <text>No. {{$index + 1}}, {{v.nickname}}
  3. </text>
  4. </div>```
  5.  
  6. ```html
  7.  
  8. <div repeat="{{(k, v) in list}}">
  9. <text>No. {{k + 1}}, {{v.nickname}}</text>
  10. </div>

使用 track-by 追踪特殊的属性

通常情况下,当更新repeat数组时,所有数组元素关联的组件节点都会被重新渲染。如果其中部分节点的数据在更新前后未发生变更,那么最好是让这些节点保持原样,仅更新数据有变化的节点,weex提供了track-by属性能帮您轻松搞定。

注意: track-by属性的设置不支持数据绑定的方式

例如:

  1. <template>
  2. <container>
  3. <container repeat="{{list}}" track-by="nickname" class="{{gender}}">
  4. <image src="{{avatar}}"></image>
  5. <text>{{nickname}} - {{group}}</text>
  6. </container>
  7. </container>
  8. </template>

如前所述,当更新repeat数组时,如果检测到属性nickname的值前后一致,那么它所绑定的子节点将不被重新渲染。

简化写法

对于if和repeat的使用,可以简化处理,即if="show"和if="{{show}}"所表达的前端语义相同。

  1. <template>
  2. <container>
  3. <text if="shown">Hello</text>
  4. <text if="{{shown}}">Hello</text>
  5. </container>
  6. </template>
  7.  
  8. <script>
  9. module.exports = {
  10. data: function () {return {shown: true}}
  11. }
  12. </script>

很显然,这两个text文本会被同时显示出来。


还没有评论.