index.js:
const Koa = require("koa");
const Router = require("koa-router");
const views = require("koa-views"); //加载模板(页面);
const static = require("koa-static");// 加载资源;
const newsData = require("./data/data.json");
let app = new Koa();
let router = new Router();
app.use(views(__dirname+"/views",{
extension:"pug"
}));
app.use(static(__dirname+"/static"));
router.get("/",async ctx=>{
ctx.body = "some thing..."
})
// 新闻列表页面
router.get("/index",async ctx=>{
// 每页显示多少条?
let perPage = ctx.request.query.perPage || 5;
// 当前页码;
let p = ctx.request.query.p || 1;
// 数据的总条数;
let dataCount = newsData.length;
// 页码数 13条 每页显示5条 当前页面1页;
let pCount = Math.ceil(dataCount/perPage);
// console.log(pCount);
//根据页码显示需要呈现的数据; mysql :LIMIT 0,5; mongodb: limit(5).skip(0);
let showData = JSON.parse(JSON.stringify(newsData)).splice((p-1)*perPage,perPage);
// ctx.body = "some thing..."
await ctx.render("index",{
showData,
pCount
});
})
// 新闻详细页面;
router.get("/detail",async ctx=>{
// 1.跳转; 2.带参数;
// 接收id:注意 类型;
let id = parseInt(ctx.request.query.id) || 1;
// console.log(typeof id);
// 通过id来查询数据;
let news = newsData.filter(v=>v.id===id);
/**
* [{id:1,content....}]
*/
let detailData = news[0];
// ctx.body = "新闻详细页面";
await ctx.render("detail",detailData);
})
app.use(router.routes());
app.listen(4000);
// 作业:1.完善列表页面 (5条数据)
// 思考:2.详细页面呈现;3.分页??
// node项目构建 mvc;
// 动态页面 ; 静态页面;
index.pug:
doctype html
html(lang='en')
head
meta(charset='UTF-8')
meta(name='viewport', content='width=device-width, initial-scale=1.0')
meta(http-equiv='X-UA-Compatible', content='ie=edge')
title 文章信息展示
link(rel='stylesheet', type='text/css', href='./css/index.css')
body
.wrap
ul.news-list
each val in showData
li.news
a(href='javascript:;')
img(src=val.imgUrl, alt='')
div
h3
a(href='/detail?id='+val.id) #{val.title}
.info
span.tips
span #{val.country}
//
span.time | #{val.addTime}
.pagination
a.prev(href='javascript:;') ⌜
- for(let i=1;i<=pCount;i++)
a(href='/index?p='+i) #{i}
a.next(href='javascript:;') ⌝
detail.pug
doctype html
html(lang='en')
head
meta(charset='UTF-8')
meta(name='viewport', content='width=device-width, initial-scale=1.0')
meta(http-equiv='X-UA-Compatible', content='ie=edge')
title Document
body
.text
h1.title #{title}
.article-info #{country} 时间:#{addTime}
p.content
| #{content}