当遇到表单录入时,录入好的数据提交保存到云数据库后,在其他页面展示刚提交到数据库的数据时,今天自己尝试做一遍。
表单页面:
代码如下:
<view class="container">
<form action="" bindsubmit="addBtn">
<view class="view-li">
<label>姓名:</label>
<input type="text" name="name" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>性别:</label>
<input type="text" name="gender" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>身份证号:</label>
<input type="idcard" name="idcard" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>手机号:</label>
<input type="number" name="phoneNub" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>职业:</label>
<input type="text" name="occupation" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>目的地:</label>
<input type="text" name="destination" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<view class="view-li">
<label>交通工具:</label>
<input type="text" name="vehicle" placeholder="请输入" placeholder-class="color" class="ipt" value='{{form_info}}'></input>
</view>
<button type="primary" form-type="submit">提交</button>
<button type="primary" form-type="reset">重置</button>
</form>
</view>
js如下:
//index.js
//import WxValidate from '../../utils/WxValidate';
const app = getApp()
const db = wx.cloud.database()//调用默认云环境的数据库引用
Page({
data: {
dataObj:"",
number:'',
phoneNub:''
},
onLoad() {
},
//提交表单添加到数据库
addBtn: function(e){
var resValue=e.detail.value;
resValue.buyerCreateTime = new Date();//提交时新增默认时间,在获取数据时以时间排序
db.collection("list").add({
data:resValue,
}).then(e=>{
this.setData({
form_info: '',//提交后清空输入框数据
}),
console.log(e)
})
},
})
在提交方法里面默认增加了默认时间,在获取数据时用做以时间排序展示。提交到云数据库后的数据如下图:
接下来看下如何在其他页面获取数据并展示到页面中
<view class="view-li" wx:for="{{dataArr}}" wx:key="index">
<view>{{index+1}}、{{item.names}}</view>
<view>{{item.gender}}</view>
<view>{{item.idcard}}</view>
<view>{{item.phoneNub}}</view>
<view>{{item.occupation}}</view>
<view>{{item.destination}}</view>
</view>
//index.js
const app = getApp()
const db = wx.cloud.database()//调用默认云环境的数据库引用
var myVlu=""//声明一个为空的变量
Page({
data: {
dataArr:""
},
//获取数据并显示在页面中
getData(){
db.collection("list").orderBy("buyerCreateTime","desc").get().then(res=>{//首先获取数据集合,查询数据,
this.setData({
dataArr:res.data
})
})
},
// 生命周期函数
onLoad: function(options) {
this.getData();
},
})
在获取数据时,使用orderBy()排序,(asc正序 、desc倒序),以默认时间来排序,buyerCreateTime在上面说过了,在表单提交的时候绑定默认时间,然后在选择使用正序还是倒序。
已上便是小程序表单提交云数据库后,再获取数据库中的数据并渲染到页面上。做个笔记记录,欢迎大家点评