vuepress 搭建了一個自己的技術博客,記錄自己平時工作和學習中的一些經(jīng)驗總結,但是因為 vuepress 本身是為了方便我們快速搭建技術文檔的,直接用來做博客總覺得少了點啥東西,怎么看都像一個文檔網(wǎng)站。
本來是打算自己開發(fā)一個博客類的 vuepress 主題的,但一直也沒想好怎么去做,前幾天又突然想要給博客先生成一個文章列表。vuepress 默認的文章詳情里是有一個 lastUpdatedTime 最新更新時間的,于是順藤摸瓜先去找出 vuepress 里的這個 lastUpdatedTime 是咋獲取到的。
在 node_modules\@vuepress\plugin-git\lib\node\utils\getUpdatedTime.js 文件里找到了具體的實現(xiàn)方式,其實就是獲取的 git 提交日志里的時間,代碼如下:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUpdatedTime = void 0;
const execa = require("execa");
/**
* Get unix timestamp in milliseconds of the last commit
*/
const getUpdatedTime = async (filePath, cwd) => {
const { stdout } = await execa('git', ['--no-pager', 'log', '-1', '--format=%at', filePath], {
cwd,
});
return Number.parseInt(stdout, 10) * 1000;
};
exports.getUpdatedTime = getUpdatedTime;
但是生成文章列表我們肯定是想按照創(chuàng)建文章的時間倒序生成,其實在 getUpdatedTime.js 同級目錄里還有一個 node_modules\@vuepress\plugin-git\lib\node\utils\getCreatedTime.js,用這個方法我們就能拿到 markdown 文件的 git 創(chuàng)建時間,然后直接根據(jù)這個時間來生成文章列表就可以了。
具體實現(xiàn)步驟:
在 .vuepress/components 組件目錄下新建一個文章列表 article-list.vue 組件,因為想要做成一個分頁列表,這里在自己封裝了一個 pagination 分頁組件,直接引用第三方組件庫里的分頁組件也一樣。
注意這個列表組件里相當于只是一個模板組件,后面想要生成文章數(shù)據(jù)的時候,只用通過正則去替換掉 init 方法里 articleList 的賦值,默認是個空數(shù)組。
article-list 文章列表組件
<template>
<div>
<div class="article-list">
<a
v-for="(item, index) in pageList"
:key="index"
class="article-item"
:href="item.link"
>
<p class="title">{{ item.title }}</p>
<p class="time">{{ item.createTime }}</p>
</a>
</div>
<!-- 分頁 -->
<pagination
:page-no="page.index"
:page-size="page.size"
:total="page.total"
:continues="3"
@change-page-no="getPageNo"
@change-page-size="getPageSize"
/>
</div>
</template>
<script>
import pagination from './pagination.vue'
export default {
components: {
pagination,
},
name: 'article-list',
data() {
return {
articleList: [],
pageList: [],
page: {
index: 1,
size: 10,
total: 0,
},
}
},
created() {
this.init()
},
methods: {
init() {
this.articleList=[]
this.page.total = this.articleList.length
this.getList()
},
getPageNo(i) {
this.page.index = i
this.getList()
},
getPageSize(size) {
this.page.size = size
this.page.index = 1
this.getList()
},
getList() {
const { index, size } = this.page
this.pageList = this.articleList.slice((index - 1) * size, index * size)
}
}
}
</script>
<style lang='scss' scoped>
.article-list {
.article-item {
display: flex;
justify-content: space-between;
align-items: center;
&:not(:last-child) {
border-bottom: 1px dashed var(--c-border);
}
.title {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--c-text);
padding-left: 16px;
position: relative;
&:before {
content: "";
position: absolute;
top: 50%;
left: 2px;
width: 6px;
height: 6px;
transform: rotate(45deg);
background: var(--c-brand);
margin-top: -3px;
}
}
.time {
margin-left: 20px;
font-size: 14px;
font-weight: normal;
color: var(--c-text-lightest);
}
}
}
</style>
pagination 分頁組件
<template>
<div class="pagination">
<button
:disabled="pageNo === 1"
@click="$emit('getPageNo', pageNo - 1)"
>
上一頁
</button>
<button
v-if="startAndEndIndex.start > 1"
@click="$emit('change-page-no', 1)"
:class="{ active: pageNo === 1 }"
>
1
</button>
<button v-if="startAndEndIndex.start > 2">···</button>
<!-- 連續(xù)的頁碼 -->
<template v-for="(page, index) in startAndEndIndex.end">
<button
v-if="page >= startAndEndIndex.start"
:key="index"
:class="{ active: pageNo === page }"
@click="$emit('change-page-no', page)"
>
{{ page }}
</button>
</template>
<button v-if="startAndEndIndex.end < totalPage - 1">···</button>
<button
v-if="startAndEndIndex.end < totalPage"
:class="{ active: pageNo === totalPage }"
@click="$emit('change-page-no', totalPage)"
>
{{ totalPage }}
</button>
<button
:disabled="pageNo === totalPage"
@click="$emit('change-page-no', pageNo + 1)"
>
下一頁
</button>
<select
v-model="size"
class="select"
@change="$emit('change-page-size', size)"
>
<option v-for="s in pageSizes" :key="s" :value="s">{{ s }} 條/頁</option>
</select>
<span class="total">共 {{ total }} 條</span>
</div>
</template>
<script>
export default {
name: 'pagination',
props: {
pageNo: { // 頁碼
type: Number,
default: 1,
},
pageSize: { // 每頁個數(shù)
type: Number,
default: 10,
},
total: { // 總條數(shù)
type: Number,
default: 0,
},
continues: { // 頁碼連續(xù)出現(xiàn)的個數(shù)
type: Number,
default: 5,
},
pageSizes: { // 每頁顯示個數(shù)選擇器選項
type: Array,
default: [10, 20, 30, 40],
},
},
data() {
return {
size: 10,
}
},
computed: {
// 總頁數(shù)
totalPage() {
return Math.ceil(this.total / this.pageSize)
},
// 計算出連續(xù)頁碼的起始數(shù)字與結束的數(shù)字
startAndEndIndex() {
const { continues, pageNo, totalPage } = this
let start = 0, end = 0
// 即總頁數(shù) < 連續(xù)頁碼
if (continues > totalPage) {
start = 1
end = totalPage
} else {
start = pageNo - parseInt(continues / 2)
end = pageNo + parseInt(continues / 2)
if (start < 1) {
start = 1
end = continues
}
if (end > totalPage) {
start = totalPage - continues + 1
end = totalPage
}
}
return { start, end }
},
},
}
</script>
<style lang="scss" scoped>
.pagination {
font-size: 13px;
color: var(--c-text);
text-align: center;
margin: 10px 0 40px;
button {
min-width: 32px;
height: 28px;
padding: 0 8px;
margin: 10px 5px 0;
border: 0;
border-radius: 2px;
background: var(--c-bg-light);
outline: none;
display: inline-block;
box-sizing: border-box;
vertical-align: top;
color: var(--c-text);
cursor: pointer;
&[disabled] {
color: #c0c4cc;
cursor: not-allowed;
}
&.active {
cursor: not-allowed;
background: var(--c-brand);
color: #fff;
}
}
.total {
display: inline-block;
margin-top: 10px;
margin-left: 10px;
}
.select {
appearance: none;
-webkit-appearance: none;
outline: none;
cursor: pointer;
background: var(--c-bg);
border: 1px solid var(--c-border);
border-radius: 2px;
padding: 0 8px;
margin-left: 5px;
margin-top: 10px;
color: var(--c-text);
line-height: 26px;
&::-ms-expand,
&::-webkit-scrollbar,
&::-webkit-scrollbar-button {
display: none;
}
}
}
</style>
博客之前的側邊欄菜單 sidebar 是直接通過 sidebar.js 這個文件單獨處理的,里面有直接去遍歷博文目錄,所以直接可以在里面來同時生成文章列表就行了,完整代碼如下:
const fs = require('node:fs')
const path = require('node:path')
const IGNORE_FILE = ['guide.md', '.DS_Store'] // 不需要處理的文件
// 參考 @vuepress/plugin-git 插件通過 git log 獲取文件新建和修改時間信息
const execa = require('execa')
const getCreatedTime = async (filePath, cwd) => {
const { stdout } = await execa('git', ['--no-pager', 'log', '--diff-filter=A', '--format=%at', filePath], {
cwd,
})
return Number.parseInt(stdout, 10) * 1000
}
let articleList = []
// 自動讀取 note 文件夾目錄生成側邊欄菜單
let sidebar = [{ text: 'home', link: '/note/guide' }]
const menuList = fs.readdirSync(path.join(__dirname, '../note'))
menuList.map(m => {
if (!IGNORE_FILE.includes(m)) {
let posts = fs.readdirSync(path.join(__dirname, '../note/' + m))
let children = []
posts.map(async (n) => {
if (!IGNORE_FILE.includes(n)) {
children.push({
text: n,
link: `/note/${m}/${n}/index.md`
})
let createTimestamp = await getCreatedTime(path.join(__dirname, `../note/${m}/${n}/index.md`))
if (isNaN(createTimestamp)) createTimestamp = new Date().getTime()
const date = new Date(createTimestamp)
const year = date.getFullYear()
let month = date.getMonth() + 1
if (month < 10) month = '0' + month
let day = date.getDate()
if (day < 10) day = '0' + day
articleList.push({
title: n,
createTimestamp,
createTime: `${year}-${month}-${day}`,
link: `/note/${m}/${n}/index.html` // 注意這里路徑不能用和 sidebar 一樣的 md 文件
})
}
})
sidebar.push({
text: m,
collapsible: true,
children
})
}
})
// 寫入首頁 article-list.vue 文章列表組件數(shù)據(jù)
fs.readFile(path.join(__dirname, './components/article-list.vue'), 'utf-8', async (err, data) => {
if (err) return console.error(err)
// 按發(fā)布時間排下序
articleList.sort((a, b) => {
return b.createTimestamp - a.createTimestamp
})
let newTxt = data.replace(/this\.articleList=\[[\S\s]*\]/, `this.articleList=${JSON.stringify(articleList, null, 2)}`)
fs.writeFile(path.join(__dirname, './components/article-list.vue'), newTxt, (err, data) => {
if (err) return console.error(err)
})
})
module.exports = sidebar
開始直接在生成列表數(shù)據(jù)時直接生成的 template 模板標簽里的內(nèi)容,這樣就有點類似后端里的模板技術、jsp之類的,不過現(xiàn)在都是前后端分離,為了好維護最終還是改成只去替換組件里的 articleList 列表數(shù)據(jù),這樣 article-list 組件里可以隨意修改布局樣式交互這些, sidebar 只是提供對應的數(shù)據(jù)。
最后直接在博客首頁的 markdown 文件里引入 article-list 組件就行了:
---
home: true
heroImage: /images/logo.png
heroText:
tagline: web ? uniapp ? flutter ? electron ? wordpress ? node ? java
---
<article-list />
最終的博客首頁文章列表展示效果圖:
還是比較滿意的,后面還可以從內(nèi)容里提取出分類、摘要、圖片、作者這些信息,讓列表更加的豐富,等有空了再來完善。
者:HelloGitHub-追夢人物
在 通過 Django Pagination 實現(xiàn)簡單分頁中,我們實現(xiàn)了一個簡單的分頁導航。但效果有點差強人意,我們只能點上一頁和下一頁的按鈕進行翻頁。比較完善的分頁效果應該像下面這樣,但想實現(xiàn)這樣一種效果,Django Pagination 內(nèi)置的 API 已無能為力。接下來我們將通過拓展 Django Pagination 來實現(xiàn)下圖這樣比較完善的分頁效果。
一個比較完善的分頁效果應該具有以下特性,就像上圖展示的那樣,很多網(wǎng)站都采用了類似這種的分頁導航方式。
如果需要自己來實現(xiàn)分頁效果,我們會怎么做呢?先來分析一下導航條的組成部分,可以看到整個分頁導航條其實可以分成 7 個部分:
因此我們的思路是,在視圖中依據(jù)上述規(guī)則生成頁碼列表,然后在模板中循環(huán)顯示頁碼列表就可以了。有了思路,實現(xiàn)起來其實也并不很難。不過對于這類常見需求,別人早就幫我們實現(xiàn)好了,本著不重復造輪子的原則,直接拿來用就好。
我們第一次開始接觸 django 第三方拓展,在此之前我們一直都基于 django 本身我們提供的功能在開發(fā),然而 django 強大的地方就在于海量的第三方應用供我們挑選,幾乎大部分 web 開發(fā)中的需求,django 都能找到他人已經(jīng)寫好的第三方應用,拿來即用。
事實上,正確的 django 開發(fā)姿勢應該是這樣的:
以我們的分頁功能舉例:
首先我們上面分析了分頁需求的實現(xiàn)。然后我在 GitHub 上通過 django pagination 關鍵詞進行搜索,在比較了多個 star 數(shù)比較高的項目后,發(fā)現(xiàn) django-pure-pagination 文檔最清晰,使用最簡單,因此決定將這個應用集成到我們的博客來。值得一提的是,盡管這個應用顯示作者最后一次更新代碼在 4 年前,但我粗略瀏覽了一下源碼,發(fā)現(xiàn)其依賴的 django api 4 年來異常穩(wěn)定,所以確保能在 django 2.2 中使用。
接下來我們就來使用它,首先安裝它:
$ pipenv install django-pure-pagination
然后將它注冊到 INSTALLED_APPS 里:
INSTALLED_APPS = [
# ...
'pure_pagination', # 分頁
'blog.apps.BlogConfig', # 注冊 blog 應用
'comments.apps.CommentsConfig', # 注冊 comments 應用
]
修改一下 IndexView,讓它繼承 django-pure-pagination 提供的 PaginationMixin,這個混入類將為我們提供上述提到的分頁功能。
class IndexView(PaginationMixin, ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
paginate_by = 10
然后我們可以在 common.py 配置中配置一下分頁的效果,這是 django-pure-pagination 提供的配置項,用于個性化配置分頁效果:
# django-pure-pagination 分頁設置
PAGINATION_SETTINGS = {
'PAGE_RANGE_DISPLAYED': 4, # 分頁條當前頁前后應該顯示的總頁數(shù)(兩邊均勻分布,因此要設置為偶數(shù)),
'MARGIN_PAGES_DISPLAYED': 2, # 分頁條開頭和結尾顯示的頁數(shù)
'SHOW_FIRST_PAGE_WHEN_INVALID': True, # 當請求了不存在頁,顯示第一頁
}
在模板中需要分頁的地方,調(diào)用分頁對象的 render 方法就可以了,比如在 index.html 中:
{% if is_paginated %}
{{ page_obj.render }}
{% endif %}
注意這里 page_obj 是分頁后的對象列表,具體請參考上一篇文章的講解。render 方法會自動幫我們渲染一個預先定義好的分頁條,至此,分頁功能就完成了。
有時候預定義的分頁條并不能滿足我們的需求,我們可以通過自定義的模板來覆蓋預定義的模板。django 查找模板的順序是,首先在項目配置的模板根路徑尋找(我們項目中配的是 templates 文件夾),沒有找到的話,再去應用的 templates 目錄下尋找。分頁模板預定義的路徑為 pure_pagination/pagination.html,所以我們可以在項目模板根路徑下建立一個一模一樣的文件結構,這樣 django 就會首先找到我們的模板,從而應用我們自定義的模板,而不是預定義的模板。
在 templates 目錄下新建一個 pure_pagination\ 目錄,然后建立一個 pagination.html 文件。
接下來便是在模板中設置分頁導航了,將導航條的七個部分的數(shù)據(jù)一一展現(xiàn)即可,示例代碼如下:
<div class="text-center pagination" style="width: 100%">
<ul>
{% if page_obj.has_previous %}
<li><a href="?{{ page_obj.previous_page_number.querystring }}"
class="prev">?? </a></li>
{% else %}
<li><span class="disabled prev">?? </span></li>
{% endif %}
{% for page in page_obj.pages %}
{% if page %}
{% ifequal page page_obj.number %}
<li class="current"><a href="#">{{ page }}</a></li>
{% else %}
<li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li>
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li><a href="?{{ page_obj.next_page_number.querystring }}" class="next"> ??</a>
</li>
{% else %}
<li><span class="disabled next"> ??</span></li>
{% endif %}
</ul>
</div>
多添加幾篇文章,在示例中就可以看到分頁效果了。要使分頁導航更加美觀,通過設置其 CSS 樣式即可。
『講解開源項目系列』——讓對開源項目感興趣的人不再畏懼、讓開源項目的發(fā)起者不再孤單。跟著我們的文章,你會發(fā)現(xiàn)編程的樂趣、使用和發(fā)現(xiàn)參與開源項目如此簡單。歡迎留言聯(lián)系我們、加入我們,讓更多人愛上開源、貢獻開源
擊右上方紅色按鈕關注“web秀”,讓你真正秀起來
作為前端開發(fā),很多時候,后臺給的數(shù)據(jù)不是我們想要的,遇到好說話的,給你改,遇到那種不好說話的,只能自己動手了。今天就來給大家講講前端如何來模擬分頁,下面注釋很詳細,這里就不做過多的介紹了。
<div id="docList"></div> <div class="more" id="docLoadMore">加載更多</div>
var data = { // 分頁數(shù)據(jù) docPages: { pageNo: 1, // 當前頁碼 pageSize: 3 // 一頁多少條數(shù)據(jù) }, // 模擬數(shù)據(jù) docList: [{ name: '這是我的第1篇文章' },{ name: '這是我的第2篇文章' },{ name: '這是我的第3篇文章' },{ name: '這是我的第4篇文章' },{ name: '這是我的第5篇文章' },{ name: '這是我的第6篇文章' },{ name: '這是我的第7篇文章' },{ name: '這是我的第8篇文章' }] } $('#docLoadMore').on('click',function(){ function getHtml(name) { // html模板 var tpl = '<div class="load-li dis-flex clearfix">'+ '<span class="align-left">'+ '<img src="../images/productDetails/yh_product_wendang_icon@2x.png" / class="word-icon">'+ '</span>'+ '<span class="color-66 flex1 li-content fs-01">'+name+'</span>'+ '<span class="align-right">'+ '<img src="../images/productDetails/yh_product_xiazai_icon@2x.png" / class="load-icon">'+ '</span>'+ '</div>'; return tpl; } var pageNo = data.docPages.pageNo; var pageSize = data.docPages.pageSize; // 計算最多分多少頁 // 總條數(shù) / 一頁多少條 = 可以分多少頁 如果是小數(shù) 向上取整(Math.ceil) let maxPage = Math.ceil(data.docList.length / pageSize); // 如果頁面大于總頁數(shù)return if (pageNo > maxPage) { console.log('沒有更多了'); return; } // 計算第n頁時取第幾條到第幾條數(shù)據(jù) var startIndex = (pageNo-1) * pageSize; // 下標從0開始,所以-1 // 1:(1-1)*2=>0 // 2:(2-1)*2=>2 // 3:(3-1)*2=>4 // 4:(4-1)*2=>6 var endIndex = pageNo * pageSize - 1; // 1: 1*2=>2 // 2: 2*2=>4 // 3: 3*2=>6 data.docPages.pageNo ++; // 根據(jù)下標找到對應的頁碼的數(shù)據(jù) var newPage = vm.data.docList.slice(startIndex, endIndex+1); let html = ''; newPage.map(function(item){ html += getHtml(item.name); }); // 向元素后面插入準備好的html內(nèi)容 $('#docList').append(html); })
中間有部分是模板,看的不是很清楚,看下面截圖。
上面代碼沒有初始化第一頁數(shù)據(jù),點擊一下才會出來第一頁的數(shù)據(jù),所以可以在頁面加載完畢,自動觸發(fā)一下點擊事件
$('#docLoadMore').trigger('click');
是不是很簡單了,只要自己動手操作,發(fā)現(xiàn)事實都很簡單。
喜歡小編的點擊關注,了解更多知識!
源碼地址請點擊下方“了解更多”
*請認真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。