WeChat small program data list rendering: easy to understand wx:for (local data rendering case)

Keywords: Attribute

Mainly solve the problem of data list rendering

1,
This is an official case.
wx:for
Using wx:for control attribute to bind an array on a component, the component can be rendered repeatedly using the data of each item in the array.

The subscript variable name of the current item of the default array defaults to index, and the variable name of the current item of the array defaults to item.

<view wx:for="{{array}}">
      {{index}}: {{item.message}}
    </view>
    
    
    Page({
      data: {
        array: [{
          message: 'foo',
        }, {
          message: 'bar'
        }]
      }
    })
    
    
    wx:for-item You can specify the variable name of the current element of the array.
    //Using wx:for-index You can specify the variable name of the current subscript of the array:
    <view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
      {{idx}}: {{itemName.message}}
    </view>

2. Next, the local data is rendered with real cases, and the difference between changing variable names is explained.

  1. Create a new data file in the project.
 var news= [
    {
        "id":"1",
        "new" :"This is the first message."
    },
    {
        "id":"2",
        "new": "This is the second message."
    },
    {
        "id":"3",
        "new": "This is the third message."
    }

]
module.exports = {news}; //Keep that in mind and expose the data.

3. Then on the page that needs to be rendered

mine.js

var jsonData = require('../../datas/news.js'); //Introduce data code
Page({
  data: {
  },
  onLoad: function () {
    var that = this;
    this.setData({
      news: jsonData.news
    });
    }
})

mine.wxml

 <!-- Default mode
       <view class="newslist" wx:for="{{news}}" 
        >    
          <text>
          //Subscript {{index}}  
         //Print ID {{item.id}} 
        //Output message {{item.new}}
        </text> 
       </view>
-->

      <view wx:for="{{news}}" wx:for-index="idx" wx:for-item="item2">
          <text class="newslist" >
            //Subscript {idx}}
            ID {{item2.id}}
            //Output message {{item2.new}}
          </text> 
      </view>

4. Both of the above output modes are

Posted by Azazeal on Fri, 04 Oct 2019 15:51:08 -0700