vue学习之留言板实例

留言板实例

  • 知识点:
    • 渲染html页面时,设置root为根目录;
     exports.showindex=(req,res)=>{
         res.sendFile("index.html",{root:"./"});
     };
    
    • 前端用vue-reosurce发送请求,后台用express创建服务器,利用mongodb数据库存储数据;
    • 前端a标签中的href发送get请求,发送请求时如何提交参数,配合动态数据;如<a :href='"/deldata?id="+item._id' class="btn btn-danger">删除</a>;其中item为动态数据;
    • js模块导出变量,用module.exports=db;则在其他js文件中导入此文件,变量即db;
    • vue生命周期中,数据在created()和beforeMount()函数中获取;
    • 若提交数据时,传入的time参数为毫秒数,即设置fields.time=new Date().getTime();则需要将获取的time值转化为特定格式的日期;
     getData(){
         this.$http.get(`/getdata?page=${this.page}&pageamount=${this.pageamount}`).then(res=>{
             var ary=res.body;
             //时间转化,0=》00;1=》01
             function todate(time) {
                 if(time>=0 && time<=9){
                     return "0"+time;
                 }else{
                     return ""+time;
                 }
             }
             //将毫秒数转化为特定格式的日期;
             function changeTime(time){
                 var commonTime = "";
                 if(time){
                     var unixTimestamp = new Date(time*1) ;
                     Date.prototype.toLocaleString = function() {
                         return this.getFullYear() + "-" + todate(this.getMonth() + 1) + "-" + todate(this.getDate()) + " " + todate(this.getHours()) + ":" + todate(this.getMinutes()) + ":" + todate(this.getSeconds());
                     };
                     commonTime = unixTimestamp.toLocaleString();
                 }
                 return commonTime;
             }
             //通过map遍历数组,然后修改里面的time值;
             ary=ary.map(function (item) {
                 item.time=changeTime(item.time);
                 return item;
             });
             //获取数组数据赋值给this.dataAry
             this.dataAry=ary;
         })
     },
    
  • 代码:
    • index.html文件代码:
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <title>vue留言板实例</title>
         <link rel="icon" type="image/x-icon" href="img/icon.jpg">
         <link rel="stylesheet" href="css/bootstrap.css">
     </head>
     <body>
     <div class="container" id="app">
         <h1 style="text-align: center;margin-top: 50px;">Vue分页留言板</h1>
         <form>
             <div class="form-group">
                 <label for="title" class="h3">标题</label>
                 <input type="text" class="form-control" id="title" name="title" placeholder="请输入留言标题" v-model="title">
             </div>
             <div class="form-group">
                 <label for="comment" class="h3">内容</label>
                 <textarea name="comment" id="comment" class="form-control" placeholder="请输入留言内容" cols="30" rows="6" v-model="comment"></textarea>
             </div>
             <button type="button" class="btn btn-primary" @click="subData">提交留言</button>
         </form>
         <!--分页区域-->
         <ul class="pagination">
             <li v-for="(item,index) in pageCount" :class={active:index===page}><a href="" @click.prevent="getPage(index)">{{item}}</a></li>
         </ul>
         <!--留言区域-->
         <ul class="list-group">
             <li class="list-group-item" v-for="(item,index) in dataAry">
                 <p>【标题】:{{item.title}}</p>
                 <p>【内容】:{{item.comment}}</p>
                 <p>【时间】:{{item.time}}</p>
                 <p><a :href='"/deldata?id="+item._id' class="btn btn-danger">删除</a></p>
             </li>
         </ul>
     </div>
     <script src="js/vue.js"></script>
     <script src="js/vue-resource.js"></script>
     <script>
         var vm=new Vue({
             el:"#app",
             data:{
                 title:"",
                 comment:"",
                 dataAry:[],
                 pageamount:3,
                 pageCount:0,
                 page:0
             },
             methods:{
                 //1.发送post请求,提交留言数据
                 subData(){
                     //判断输入框内的内容不能为空
                     this.$http.post("/subdata",{
                         title:this.title,
                         comment:this.comment
                     }).then(res=>{
                         this.title=this.comment="";
                         alert(res.body);
                         window.location.href="/";
                     })
                 },
                 //2.获取数据的总个数
                 getCount(){
                     //需要传参
                     this.$http.get("/getcount").then(res=>{
                         var count=res.body;//字符串类型的数字;
                         this.pageCount=Math.ceil(count/this.pageamount);
                     })
                 },
                 //3.获取指定页码内的数据
                 getData(){
                     this.$http.get(`/getdata?page=${this.page}&pageamount=${this.pageamount}`).then(res=>{
                         //获取数组数据赋值给this.dataAry
                         this.dataAry=res.body;
                     })
                 },
                 //4.点击页码,更新this.page值
                 getPage(index){
                     this.page=index;
                     this.getData();//重新获取数据,动态操作页面;
                 }
             },
             beforeMount(){
                 this.getCount();
                 this.getData();
             }
         })
     </script>
     </body>
     </html>
    
    • app.js代码:
     const express=require("express");
     //引入自定义模块
     const router=require("./controller/router");
     const app=express();
     
     //设置静态资源目录,引入js文件
     app.use(express.static("./public"));
     
     //渲染html页面
     app.get("/",router.showindex);
     //提交数据
     app.post("/subdata",router.subData);
     //获取数据总个数
     app.get("/getcount",router.getCount);
     //获取数据
     app.get("/getdata",router.getData);
     //删除数据
     app.get("/deldata",router.delData);
     
     app.listen(2525);
    
    • router.js代码:
     const db=require("../model/db");
     const formidable=require("formidable");
     const sd=require("silly-datetime");
     const ObjectId=require("mongodb").ObjectId;
     
     exports.showindex=(req,res)=>{
         res.sendFile("index.html",{root:"./"});
     };
     exports.subData=(req,res)=>{
         //formidable接受post请求数据
         var form= new formidable.IncomingForm();
         form.parse(req,function (err, fields, files) {
             //添加时间戳
             fields.time=sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
             //插入数据库
             db.insertOne("comment",fields,function (err, result) {
                 if(err){
                     console.log(err);
                     return;
                 }
                 res.send("提交留言成功");
             })
         });
     };
     exports.getData=(req,res)=>{
         //解构赋值
         var {page,pageamount}=req.query;
         //从数据库获取数据
         db.find("comment",{},{"sort":{"time":-1},page,pageamount},function (err, result) {
             if(err){
                 console.log(err);
                 return;
             }
             res.send(result);
         })
     };
     exports.getCount=(req,res)=>{
         db.count("comment",{},function (err, count) {
             //res.send()中不能放数字类型
             res.send(count.toString());
         })
     };
     exports.delData=(req,res)=>{
         var id=req.query.id;
         db.deleteMany("comment",{_id:ObjectId(id)},function (err, result) {
             if(err){
                 console.log(err);
                 return;
             }
             res.redirect("/");
         })
     };
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容