本案例主要应用事件绑定(bindTap)、本地缓存的保存(setStorage)与获取(getStorage),实现留言板的添加留言、删除留言、添加留言后自动保存、刷新后自动读取留言等功能。
案例效果如下:
制作步骤如下:
1.在app.json文件中添加liuyanban文件夹的路径,app.json的代码如下:
{
"pages":[
"pages/liuyanban/liuyanban",
"pages/index/index",
"pages/logs/logs"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#333",
"navigationBarTitleText": "简单留言板",
"navigationBarTextStyle":"white"
}
}
2. liuyanban.wxml的代码如下:
<view class='message1'>
<!--显示部分-->
<text class='infoTitle'>留言信息</text>
<view class='show' wx:for="{{messageData}}"wx:key="{{index}}">
<view class='show-item' >
<text class='t2'>{{item.message}}</text>
<icon data-index='{{index}}' class='delBtn' type='cancel' bindtap='delMessage'></icon>
</view>
</view>
<text class='lyInfo' wx:if="{{messageData==0}}">暂无留言...</text>
<!-- 编辑部分-->
<text class='infoTitle'>添加留言</text>
<view class='cont1'>
<textarea bindinput="inputValue" class='t1' value='{{inputVal}}' placeholder='写点什么吧' placeholder-class='place1'></textarea>
<button size='mini' type='warn' bindtap="addMessage" class='addBtn'>提交</button>
</view>
</view>
3.liuyaban.wxss的代码如下:
.message1{
margin:0 10rpx;
}
.cont1{
display: flex;
flex-direction:column;
}
.t1{
border: solid 1px #ccc;
padding:10rpx;
margin: 20rpx 0;
height:200rpx;
}
.addBtn{
margin: 10px 0 0 0;
width:150rpx;
border-radius:0rpx;
}
.place1{
color:#ccc;
}
.show{
margin:20px 0 0 0;
}
.show-item{
background:#ddd;
height:100%;
overflow:auto;
margin:10px 0;
padding:5px;
}
.t2{
float:left;
}
.delBtn{
float:right;
margin:5px 5px 5px 0;
}
.lyInfo{
display: block;
margin:20px 0 0 0;
}
.infoTitle{
background:#f60;
display: block;
width:25%;
height:30px;
line-height: 30px;
padding:0 0 0 10px;
color:#eee;
margin:10px 0;
}
4.liuyanban.js的代码如下:
Page({
data: {
messageData:[],
inputVal:''
},
inputValue: function (ev) {
this.setData({
inputVal: ev.detail.value
});
},
//添加
addMessage:function(){
var info=this.data.messageData;
info.push({
message:this.data.inputVal
});
this.setData({
messageData:info,
inputVal:''
})
// 存储
wx.setStorage({
key: 'messageData',
data: info,
})
},
//删除
delMessage:function(ev){
var m=ev.target.dataset.index;
var info = this.data.messageData;
info.splice(m,1);
this.setData({
messageData:info
});
wx.removeStorage({
key: 'messageData',
})
},
//显示
onLoad:function(info){
var that=this;
wx.getStorage({
key: 'messageData',
success: function (res) {
//console.log(res.data);
that.setData({
messageData:res.data
});
}
})
}
})
至此,案例制作完成。