WeChat applet local json data is displayed on the page

Create a new json file and use module.exports to define the export, otherwise the json data cannot be read by other files. There is also a small detail that needs to be noted. The local json data is placed in the js file, not the json file, otherwise an error will be reported.

// 本地模拟json数据
var jsonData = [
  {
    "id":1,
    "name": "Tom1"
  },
  {
    "id": 2,
    "name": "Tom2"
  },
  {
    "id": 3,
    "name": "Tom3"
  },
  {
    "id": 4,
    "name": "Tom4"
  },
  {
    "id": 5,
    "name": "Tom5"
  }
]

// 定义数据出口
module.exports = {
  dataList: jsonData
}

wxml code

<view>
  <block wx:for="{{dataList}}" wx:key="{{index}}">
      <view>{{item.id}}: {{item.name}}</view>
  </block>
</view>

The local json data is introduced in the js code. The parameter behind require is the file path of the entry file, but it must be a relative path, not an absolute path.

// 引入本地文件
var localData = require("../../static/localdata.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
  },
  //在这里加载本地json数据
  onLoad: function () {
    this.setData({
      //localData.dataList获取本地localdata.js里定义的dataList数据,并赋值给dataList
      dataList: localData.dataList
    });
  }
})
Published 21 original articles · won praise 1 · views 7809

Guess you like

Origin blog.csdn.net/eva_feng/article/details/105174380