在微信小程序中,通过 JSON 配置来生成自定义表单和自定义表格是一种高效的方式,可以减少开发工作量并提高代码的可维护性。以下是一个基本的示例,展示如何通过 JSON 配置来生成自定义表单和自定义表格。
自定义表单假设我们有一个 JSON 配置文件 formConfig.json,内容如下:
{
"formItems": [
{
"type": "input",
"label": "姓名",
"name": "name",
"placeholder": "请输入姓名"
},
{
"type": "input",
"label": "年龄",
"name": "age",
"placeholder": "请输入年龄"
},
{
"type": "radio",
"label": "性别",
"name": "gender",
"options": [
{ "label": "男", "value": "male" },
{ "label": "女", "value": "female" }
]
},
{
"type": "checkbox",
"label": "兴趣",
"name": "interests",
"options": [
{ "label": "阅读", "value": "reading" },
{ "label": "运动", "value": "sports" },
{ "label": "音乐", "value": "music" }
]
}
]
} 在小程序的页面中,我们可以通过以下方式来生成表单:
<!-- form.wxml -->
<form bindsubmit="formSubmit">
<block wx:for="{{formItems}}" wx:key="index">
<view class="form-item">
<label>{{item.label}}</label>
<input wx:if="{{item.type === 'input'}}" name="{{item.name}}" placeholder="{{item.placeholder}}" />
<radio-group wx:if="{{item.type === 'radio'}}" name="{{item.name}}">
<label wx:for="{{item.options}}" wx:key="index">
<radio value="{{item.value}}" />{{item.label}}
</label>
</radio-group>
<checkbox-group wx:if="{{item.type === 'checkbox'}}" name="{{item.name}}">
<label wx:for="{{item.options}}" wx:key="index">
<checkbox value="{{item.value}}" />{{item.label}}
</label>
</checkbox-group>
</view>
</block>
<button formType="submit">提交</button>
</form> // form.js
Page({
data: {
formItems: []
},
onLoad: function () {
// 加载JSON配置
wx.request({
url: 'path/to/formConfig.json',
success: (res) => {
this.setData({
formItems: res.data.formItems
});
}
});
},
formSubmit: function (e) {
console.log('表单数据:', e.detail.value);
}
}); 自定义表格假设我们有一个 JSON 配置文件 tableConfig.json,内容如下:
{
"columns": [
{ "title": "姓名", "dataIndex": "name" },
{ "title": "年龄", "dataIndex": "age" },
{ "title": "性别", "dataIndex": "gender" },
{ "title": "兴趣", "dataIndex": "interests" }
],
"dataSource": [
{ "name": "张三", "age": 25, "gender": "male", "interests": ["reading", "sports"] },
{ "name": "李四", "age": 30, "gender": "female", "interests": ["music"] }
]
} 在小程序的页面中,我们可以通过以下方式来生成表格:
<!-- table.wxml -->
<view class="table">
<view class="table-header">
<view wx:for="{{columns}}" wx:key="index" class="table-cell">{{item.title}}</view>
</view>
<view class="table-body">
<view wx:for="{{dataSource}}" wx:key="index" class="table-row">
<view wx:for="{{columns}}" wx:key="index" class="table-cell">
{{item[item.dataIndex]}}
</view>
</view>
</view>
</view> // table.js
Page({
data: {
columns: [],
dataSource: []
},
onLoad: function () {
// 加载JSON配置
wx.request({
url: 'path/to/tableConfig.json',
success: (res) => {
this.setData({
columns: res.data.columns,
dataSource: res.data.dataSource
});
}
});
}
}); 通过这种方式,你可以通过 JSON 配置文件来动态生成自定义表单和自定义表格,从而提高开发效率和代码的可维护性。
网友回复


