Mock.js的应用
一、生成10篇文章
一)代码段
// 生成10篇文章的代码
//-------------------//
const Mock = require("mockjs");
const titles = {
// 1文章id
'id|+1':1,
//2栏目id
column:'@integer(100,200)',
// 3文章标题
username: "@ctitle(3,8)",
//4发布日期
ReleaseDate:`@date(yyyy年MM月dd日)`,
//5作者
author:"@cname",
//6简介
briefintroduction:"@csentence(50)",
//7文章内容
Articlecontent:"@cparagraph(50)",
// 生成图片占位符
img3: "@image('200x200','#f00','#fff',''php.cn')",
//生成域名
url:'@url',
};
const opts={
'titles|10':[titles],
}
const data = Mock.mock(opts);
console.log(JSON.stringify(data, null, 4));
二)生成的效果图
二、文章的渲染
一)代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文章渲染</title>
</head>
<body>
<button onclick="getData()">请求文章数据</button>
<table border="1">
<caption>文章</caption>
<thead>
<tr>
<td>id</td>
<td>栏目</td>
<td>题目</td>
<td>发布日期</td>
<td>作者</td>
<td>文章简介</td>
<td>文章内容</td>
<td>图片</td>
<td>链接</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
async function getData(){
const response =await fetch('titles.json')
const titles = await response.json()
console.log(titles)
const tbody =document.querySelector('tbody')
titles.forEach((title)=>{
const data=`
<tr>
<td>${title.id}</td>
<td>${title.column}</td>
<td>${title.username}</td>
<td>${title.ReleaseDate}</td>
<td>${title.author}</td>
<td>${title.briefintroduction}</td>
<td>${title.Articlecontent}</td>
<td>${title.img3}</td>
<td>${title.url}</td>
</tr>
` tbody.insertAdjacentHTML('beforeend',data)
})
}
window.onload = getData()
</script>
</body>
</html>
二)效果图