留言板的实现

需求分析

留言板是一款能实现浏览留言、发表留言、删除留言、发表留言和编辑留言的小程序,用户能够浏览当前的已留言内容,并且能按照时间的升序来查看最新的留言内容;能够发表自己的留言内容,在留言发表页填写相关项后即可发表,并能查看到新留言内容;能够删除不需要的留言;能够修改留言内容。因此,简单留言板的功能主要为显示留言、发表留言删除留言和编辑留言。

视图层设计

根据功能需求分析,共设计4个页面:首页(显示留言页)、发表留言页、编辑留言页和详情页

数据库设计

据留言板功能,设计数据库表名为test,其中设计的字段有id(编号)、ide(标题)ontent(内容)、image(图像)、count(次数)5个字段,通过 Bmob后端云设计。

代码实现

首页

ym.wxml

<image class="toWrite " bindtap="toAddDiary" src="../image/ss.jpg" style="width: 300px;" />
<!-- 显示留言 -->
<view class="page">
  <scroll-view lower-threshold="800" bindscrolltolower="pullUp-Load" upper-threshold="0 " scroll-y="true" style="height: {{win-dowHeight}}px;">
    <view class="page__bd">
      <button style="width: 120px;height: 60px; border: 1px saddlebrown;">
        <view class="weui-panel__hd" style="text-align: center;">留言列表</view>
      </button>
      <view>
        <block wx:if="{{diaryList.length >0}}">
          <navigator class="weui-media-box weui-media-box_text" wx:for="{{diaryList}}" wx:key="diaryItem" url="/pages/index /detail? ob-jectId={{item.objectId}}&count={{item.count}}">
            <view class="title">
              主题:{{item.title}}</view>
            <view class="content">留言内容:{{item.content}}</view>
            <view class="info">
              <view class="time">时间:{{item.updatedAt}}</view>
              <view class="count">浏览:{{item.count}}</view>
              <view class="operate">
                <icon type="cancel dels" size="16"> </icon>
                <text class="del" catchtap="deleteDiary" data-id="iitem.objectId}}">删除</text>
                <icon type="success edits" size="16"></icon>
                <text catchtap="toModifyDiary" data-id="{{item.objectId}}" data-content="{{item.content}}" data-title="{{item.title}}">编辑</text>
              </view>
            </view>
          </navigator>
        </block>
      </view>
    </view>
  </scroll-view>
</view>
<!-- 添加留言 -->
<view class="js dialog" id="androidDialog1" style="opacity:1;" wx:if="{{writeDiary}}">
  <view class="weui-mask"></view>
  <view class="weui-dialog weui-skin_android">
    <view class="weui-dialog__hd">
      <strong class="weui-dialog__title" style="margin-left: 150px;">添加留言</strong>
    </view>
    <form bindsubmit="addDiary" report-submit="true">
      <view class="weui-dialog__bd">
        <view class="weui-cells__title" style="text-align: center;">标题</view>
        <view class="weui-cells weui-cells after-title">
          <view class="weui-cell weui-cell input">
            <view class="weui-cell__bd">
              <input class="weui-input" name="title" placeholder="请输入标题" style="text-align: center;" />
            </view>
          </view>
        </view>
        <view class="weui-cel1s title" style="text-align: center;">留言内容</view>
        <view class="weui-cells weui-cells after-title">
          <view class="weui-cell">
            <view class="weui-cell bd">
              <textarea class="weui-textarea" name="content" placeholder="请输入留言内容" style="margin-left: 130px;" />
              <view class="weui-textarea-counter" style="text-align: center;">0/200</view>
            </view>
          </view>
        </view>
        <view class="pic">
          <view class="pictext" bindtap="uppic" style="text-align: center;">添加图片</view>
          <block wx:if="{isTypeof(url)})">
            <image src="../image/ss.jpg" style="width: 400px;" />
          </block>
          <block wx:else>
            <image src="{{url}}" />
          </block>
        </view>
      </view>
      <view class="weui-dialog ft">
        <button loading="{{loading}}" class="weui-dialog__btn weui-diaLog__btn__primary" formType="info">取消</button>
        <button loading="{{loading}}" class="weui-dialog__btn weui-diaLog__btn__primary" formType="info">提交</button>
      </view>
    </form>
  </view>
</view>
<!-- 修改留言 -->
<view class="js_dialog" id="androidDialog2" style="opacity: 1;" wx:if="{{modifyDiarys}}">
  <view class="weui-mask"></view>
  <view class="weui-dialog weui-skin android">
    <view class="weui-dialog hd">
      <strong class="weui-dialog title" style="text-align: center;">修改留言</strong>
    </view>
    <form bindsubmit="modifyDiary">
      <view class="weui-dialog bd">
        <view class="weui-cells title" style="text-align: center;">标题</view>
        <input class="weui =input" name="title" value="inowTitle" placeholder="请输入标题" style="text-align: center;" />
        <view class="weui-cells title" style="text-align: left;">留言内容</view>
        <view class="weui-cells weui-cells after-title">
          <view class="weui-cell">
            <view class="weui-cell bd">
              <textarea class="weui-textarea" name="content" value="{{nowContent}}" placeholder="请输入留言内容" style="margin-left: 150px;" />
              <view class="weui-textarea-counter" style="text-align: center;" style="text-align: center;">0/200 </view>
            </view>
          </view>
        </view>
      </view>
      <view class="weui-dialog ft">
        <view class="weui-dialog btn weui -dialog btn_default" bindtag="noneWindows">取消</view>
        <button loading="{{loading}}" class="weui-dialog btn weui-diaLog btn primary" formType="submit">提交</button>
      </view>
    </form>
  </view>
</view>

ym.js

//引入Bmob逻辑文件及初始化数据
var Bmob = require('../../utils/bmob.js');
var common = require('../../utils/common.js'); 
var app = getApp(); 
var that; 
var url = ""
 Page({
data:{
writeDiary:false,//写留言 
loading:false,
windowHeight:0,//定义窗口高度 
windowWidth:0,//定义窗口宽度
limit:10,	//定义数据提取条数	
diaryList:[],//定义数据列表 
modifyDiarys:false
},
//获取并显示留言数据
onShow:function(){
  getList(this);
  wx.getSystemInfo({ success:(res) => { that.setData({
  windowHeight:res.windowHeight, windowWidth:res.windowWidth
  })
}
  })
  /*
  *获取数据*/
  function getList(t,k){ 
    that =t;
  var Diary = Bmob.Object.extend("test");//数据表 
  var query = new Bmob.Query(Diary); 
  var queryl = new Bmob.Query(Diary);
  
  query. descending('createdAt'); query.include( "own")//查询所有数据
  query.limit(that.data.limit);
  
  var mainQuery = Bmob.Query.or(query);
  mainQuery.find({
  success:function(results){//循环处理查询到的数据
  console.log(results); 
  that.setData({
  diaryList:results
})
},
  error:function(error){
  console.log("查询失败:"+error.code +"" + error.message);
}
  });
}
//添加数据
 
},
toAddDiary:function() {
  that.setData({
  writeDiary:true
  })
},
  //添加图片
  uppic:function(){
  var that = this;
  wx.chooseImage({
  count:1,//默认9
  sizeType:['compressed'],//可以指定是原图还是压缩图,默认二者都有
  sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有
  success:function(res){
  var tempFilePaths=res.tempFilePaths;
  if(tempFilePaths.length >0){
  var newDate =new Date();
  var newDateStr=newDate.toLocaleDateString();//获取当前日期做文件主
  var tempFilePath=[tempFilePaths[0]];
  var extension=/\([^.]*)$/.exec(tempFilePath[0]);//获取文件扩展名
  if(extension){
  extension =extension[1].toLowerCase();
  }
  var name =newDateStr+"."+extension;//上传的图片的别名
  var file = new Bmob.File(name,tempFilePaths);
  file.save().then(function(res){
    console.log(res.url());
  url = res.url();
  that.setData({
    url:ur1
  })
   },
   function(error){
  console.log(error);
   }
  )
}
}
  })
},
  //添加留言数据
  addDiary:function(event){
  var title =event.detail.value.title;
  var content=event.detail.value.content;
  var formId =event.detail.formId;
  console.log("event".event)
if(! title){
common.showTip("标题不能为空","loading");
elseif(! content)
common.showTip("内容不能为空","loading");
}
else
that.setData({
loading:true
})
var currentUser=Bmob.User.current();
var User =Bmob.Object.extend("User");var UserModel=new User();
//增加留言
var Diary =Bmob.Object.extend("happy");//数据表 
var diary =new Diary();
diary.set("title",title);//保存title字段内容
diary.set("formId",formId);//保存 formId
diary.set("content",content);//保存content字段内容
diary.set("image",url)//保存图片地址
diary.set("count",1)//保存浏览次数
if(currentUser){
 
UserModel.id =currentUser.id;
diary.set("own",UserModel);
}
//添加数据,第一个入口参数是nu11
diary.save(null,{
success:function(result){
  common.showTip('添加日记成功');
  that.setData({
    writeDiary:false,
    loading:false
  })
    var currentUser =Bmob.User.current();
    that.onShow();
  },
    error:function(result,error){//添加失败
    common.showTip('添加留言失败,请重新发布','loading');
    }
});
},
 
    //删除留言
deleteDiary:function(event){
var that =this;
var objectId=event.target.dataset.id;
wx.showModal({
title:'操作提示',
content:'确定要删除要留言?',
success:function(res){
if(res.confirm){
//删除留言
var Diary = Bmob.Object.extend("happy");
//创建查询对象,入口参数是对象类的实例
 
var query =new Bmob.Query(Diary);
query.get(objectId,{
  success:function(object){
//The object was retrieved successfully.
 
object.destroy({
success:function(deleteObject){
console.log('删除留言成功');
getList(that)
},
error:function(object,error){
  console.log('删除留言失败');
}
});
},
error,function(object,error){
console.log("query object fail");
}
});
}
}
})
},
toModifyDiary:function(event){
  var nowTile =event.target.dataset.title;
  var nowContent =event.target.dataset.content;
  var nowId =event.target.dataset.id;
that.setData({
modifyDiarys :true,
nowTitle:nowTile,
nowContent:nowContent,
nowId:nowId
})
modifyDiary,function(e){
  var t =this;
  modify(t,e)
  function modify(t,e){
    var that = t;//修改日记
   var modyTitle = e.detail.value.title;
   var modyContent = e.detail.value.content; 
   var objectId =e.detail.value.content; 
   var thatTitle = that.data.nowTitle;
   var thatContent= that.data.nowContent;
   if((modyTitle != thatTitle ||modyContent != thatContent))
   { if(modyTitle == "" ||lmodyContent == ""){
   common.showTip('标题或内容不能为空','1oading');}
   else {
   console.log(modyContent)
   var Diary = Bmob.Object.extend("happy"); 
   var query = new Bmob.Query(Diary);
   //这个id是要修改条目的id,你在生成这个存储并成功时可以获取到,请看前面的文档
   query.get(that.data.nowId,{
   success:function(result){
   
   //回调中可以取得这个GameScore对象的一个实例,然后就可以修改它了
   result.set('title',modyTitle);
   result.set('content',modyContent);
    result.save();
   common.showTip('留言修改成功','success',function(){ that.onShow(); that.setData({
   modifyDiarys:false
   })
  });
  },
   error:function(object,error){
  }
  });
   }
   elseif(modyTitle == "" ||lmodyContent == "");{
    common.showTip('标题或内容不能为空','1oading');
    }
  }
  
    else {
    that.setData({
    modifyDiarys:false
    })
    common.showTip('修改成功','loading');
    }
  }
  }
},
 
})

ym.wxss

 
page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.scrollarea {
  flex: 1;
  overflow-y: hidden;
}
 
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #aaa;
  width: 80%;
}
 
.userinfo-avatar {
  overflow: hidden;
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}
 
.usermotto {
  margin-top: 200px;
}
/* .toWrite{
  position: absolute;
  left: 30px;
  width: 300px;
  height: 300px;
} */
 
.avatar-wrapper {
  padding: 0;
  width: 56px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}
/* .weui-panel__hd{
  margin-top: 330px;
  margin-left: 130px;
} */
 
.avatar {
  display: block;
  width: 56px;
  height: 56px;
}
 
.nickname-wrapper {
  display: flex;
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
  border-top: .5px solid rgba(0, 0, 0, 0.1);
  border-bottom: .5px solid rgba(0, 0, 0, 0.1);
  color: black;
}
 
.nickname-label {
  width: 105px;
}
 
.nickname-input {
  flex: 1;
}
详情页

detail.js

var Bmob = require('../../utils/bmob.js');
 Page({ data:{
  rows:{} //留言详情
},
  onLoad:function(e){
  //页面初始化options为页面跳转所带来的参数
  console.log(e.objectId) 
  var objectid = e.objectid; 
  var newcount =e.count; 
  var that = this;
  
  var Diary = Bmob.Object.extend("test"); 
  var query = new Bmob.Query(Diary);
  
  query.get(objectId,{
  success:function(result) {
  console.log(result);
  
  that.setData({ rows:result,})
  
  newcount = parseInt(newcount)+1//浏览次数加1 
  result.set("count",newcount)//保存浏览次数 result.save()
  },
  error:function(result,error){ console.log("查询失败");
  }
  });
}
 })

detail.wxml

<view class= "page">
<view>
<view>
<view style="width: 200px;">留言主题:</view>
<view>{{rows.title}}</view><view>
<view>留言内容:</view>
<view>{{rows.content}}</view>
<view class = "pic">
<image  src="{{rows.image}}"/></view><view>
浏览次数:{{rows.count}}</view >
<view>创建时间:{{rows.createdAt}} </view>
</view></view></view>
<view class="footer">
<text> Copyright©2017-2019www.smartbull.cn</text></view></view>

detail.wxss

page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.scrollarea {
  flex: 1;
  overflow-y: hidden;
}
.log-item {
  margin-top: 20rpx;
  text-align: center;
}
.log-item:last-child {
  padding-bottom: env(safe-area-inset-bottom);
}
配置

app.js

// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  globalData: {
    userInfo: null
  }
})
var Bomb = require('utils/bmob.js')
Bomb.initialize("8fb9bebf2790e58070b9c700b0715965","5b9d3cba2b4695ac4040ba988146c463");
App({
  
})

app.json

{
  "pages": ["pages/Ym/ym",
    "pages/detail/detail",
    
    "pages/delete/delete"
    
  ],
  "window": {
    "backgroundTextStyle":"light",
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "小小留言板",
    "navigationBarBackgroundColor": "#3891f8"
  },
  "style": "v2",
  "componentFramework": "glass-easel",
  "sitemapLocation": "sitemap.json",
  "lazyCodeLoading": "requiredComponents"
}
结果 

 

  • 17
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现一个基本的 Node.js 留言,你需要使用以下技术和步骤: 技术: 1. Node.js 2. Express.js 3. MongoDB 步骤: 1. 首先,安装 Node.js 和 MongoDB,并创建一个新的 Node.js 项目。 2. 在项目目录下,使用 npm 安装 express 和 mongoose 模块。Express 是一个 Node.js 的 web 框架,用于处理 HTTP 请求和响应。Mongoose 是一个 Node.js 的 MongoDB 驱动程序,用于连接、操作 MongoDB 数据库。 3. 在项目的根目录下,创建一个名为 index.js 的文件,并在其中导入 express、mongoose 和 body-parser 模块。 4. 创建一个新的 Express 应用程序,并定义路由,其中包括 GET 和 POST 请求的处理程序。GET 请求用于显示页面和获取现有留言,POST 请求用于提交新留言。 5. 创建一个名为 Message 的 MongoDB 模型,用于在数据库中保存和检索留言。 6. 在表单中使用表单控件,如 input、text area 和 button,用于输入和提交留言。 7. 创建一个名为 views 的目录,并在其中创建一个名为 index.ejs 的文件,用于定义留言的 HTML 和 CSS 样式。 8. 在 index.js 文件中加载文件 index.ejs,并使用 res.render() 方法将 HTML 渲染到客户端。 9. 测试应用程序,确保它能够运行并在数据库中保存和检索留言。 下面是一个简单的 Node.js 留言应用程序示例: index.js ```javascript const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const Message = require('./models/message'); mongoose.connect('mongodb://localhost:27017/messages', { useNewUrlParser: true }) .then(() => console.log('Connected to database')) .catch(() => console.log('Connection failed')); const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: false })); app.get('/', (req, res, next) => { Message.find() .then(messages => { res.render('index', { messages: messages }); }) .catch(err => { console.log(err); res.status(500).send('Error occurred'); }); }); app.post('/', (req, res, next) => { const message = new Message({ name: req.body.name, message: req.body.message }); message.save() .then(() => { res.redirect('/'); }) .catch(err => { console.log(err); res.status(500).send('Error occurred'); }); }); app.listen(3000, () => { console.log('Server started on port 3000'); }); ``` message.js ```javascript const mongoose = require('mongoose'); const messageSchema = mongoose.Schema({ name: { type: String, required: true }, message: { type: String, required: true } }); module.exports = mongoose.model('Message', messageSchema); ``` views/index.ejs ```html <!doctype html> <html> <head> <title>Guest Book</title> <style> body { font-family: Verdana, sans-serif; } form { margin-bottom: 10px; border: 1px solid black; padding: 5px; background-color: #f2f2f2; } label { display: block; margin-bottom: 5px; } input[type="text"], textarea { width: 100%; padding: 5px; margin-bottom: 10px; } input[type="submit"] { background-color: #4CAF50; color: white; font-weight: bold; border: none; border-radius: 5px; padding: 10px 20px; cursor: pointer; } input[type="submit"]:hover { background-color: #3e8e41; } .messages { border: 1px solid black; padding: 5px; background-color: #f2f2f2; } h1 { font-size: 24pt; } h2 { font-size: 18pt; } </style> </head> <body> <h1>Guest Book</h1> <form method="post" action="/"> <h2>Add a Message</h2> <label>Your Name:</label> <input type="text" name="name" required> <label>Your Message:</label> <textarea name="message" required></textarea> <input type="submit" value="Submit"> </form> <div class="messages"> <% messages.forEach(function(message) { %> <h2><%= message.name %></h2> <p><%= message.message %></p> <% }); %> </div> </body> </html> ``` 在执行完上面的步骤后,你应该就可以看到一个简单的 Node.js 留言应用程序。用户可以提交新的留言并显示现有留言。通过这个简单的示例,你可以了解如何使用 Node.js、Express.js 和 MongoDB 实现一个基本的 web 应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值