- 當(dāng)你在豐富自己的博客的時候,你想來點更加高端一點的操作,想做一個類似博客園一樣的平臺,那就得要登錄和評論功能,看看大家對自己的博客有什么更好的看法和意見。下面就給大家介紹一下怎么給自己的博客添加登錄和評論功能。
登錄
VuePress 是 Vuejs 官方提供的一個快速建設(shè)文檔站點的工具,在簡單配置好功能后,需要做的事情就剩下寫好一個個 Markdown 文檔。
因為 VuePress 提供了可以在 Markdown 中使用 Vue 的能力,所以有時候,希望可以在它的文檔功能基礎(chǔ)上增加部分常規(guī)功能,比如用戶登錄;有團隊希望公司建設(shè)的文檔內(nèi)容僅公司員工可查看,因為有可能會有涉及內(nèi)容保密的部分
VuePress 本身的安裝配置過程不再贅述,可參考官方文檔,本文將介紹使用 v-dialogs 對 VuePress 增加用戶登錄功能的進行改造,僅作為拋磚引玉,更多的需求,大家可以自由發(fā)揮想象。
安裝插件
安裝 v-dialogs 插件,將會使用它的模態(tài)窗口 (Modal) 和消息通知 (Alert) 的功能
# npm
npm i v-dialogs -D
# yarn
yarn add -D v-dialogs
創(chuàng)建登錄表單
新增 Login.vue 文件用于登錄表單,它將使用模態(tài)窗口(Modal)進行展示
這是構(gòu)建一個登錄框,基于v-dialogs插件的。
里面有一個簡單的表單判斷,代碼里面預(yù)埋了一些username和password,有符合的就放過了,你也可以換成你接口的邏輯。
# .vuepress\login\Login.vue
<template>
<div class="login-form">
<div class="form-header">賬號</div>
<div>
<input type="text" class="form-control" v-model="username">
</div>
<div class="form-header">密碼</div>
<div>
<input type="password" class="form-control" v-model="password">
</div>
<div class="btn-row">
<button class="btn" @click="login">
登錄
</button>
</div>
</div>
</template>
<script>
import { STORAGE_KEY } from './helper'
export default {
data () {
return {
username: '',
password: ''
}
},
methods: {
login ()
{
if (this.username && this.password)
{
var userAndWords = { 'user1': 'password1', 'user2' : 'password2'}
var isMatchUser = false
for(var key in userAndWords)
{
var tempUser = key;
var tempPassword = userAndWords[key]
if(this.username === tempUser && this.password === tempPassword)
{
isMatchUser = true
break;
}
}
if(isMatchUser)
{
const data = JSON.stringify({
name: this.username,
time: new Date().getTime()
})
window.localStorage.setItem(STORAGE_KEY, data)
this.$emit('close', true)
}
else{
this.$dlg.alert('抱歉,賬號密碼不對', {
messageType: 'warning'
})
}
}
else {
this.$dlg.alert('請輸入賬號密碼', {
messageType: 'warning'
})
}
}
}
}
</script>
<style lang="stylus">
.login-form
padding: 1rem
display flex
flex-direction column
box-sizing border-box
.btn-row
margin-top 1rem
.btn
padding 0.6rem 2rem
outline none
background-color #60C084
color white
border 0
.form-header
color #666
margin-bottom 0.5rem
.form-control
padding 0.6rem
border 2px solid #ddd
width 100%
margin-bottom 0.5rem
box-sizing border-box
outline none
transition border 0.2s ease
&:focus
border 2px solid #aaa
</style>
賬號和密碼驗證通過之后,我們往STORAGE_KEY寫入了一個數(shù)據(jù),以便后續(xù)刷新頁面檢查之前登錄結(jié)果,詳細判斷見下文。
helper.js
這是一個用來判斷是否登錄驗證通過的函數(shù),如果返回true就算是驗證通過,返回false那就沒驗證通過了。
# .vuepress\login\helper.js
export const STORAGE_KEY = 'user_auth_xxxxxxxxxxxx'
// Do user authorization verify
export function checkAuth ()
{
var auth = JSON.parse(localStorage.getItem(STORAGE_KEY))
return auth && Object.keys(auth).length
}
這個是判斷是否登錄過的函數(shù),說直白點,就是上面的登錄成功后,會往這個key里面寫一個對象值,每次調(diào)用頁面之前,先走這個函數(shù)做一個檢查,如果拿出來的auth是你覺得合法的,你就true通過,不然就一直繼續(xù)彈登錄框了。
其實這里,我們也可以根據(jù)自己的需要,給拿到的auth對象進一步做判斷,當(dāng)然要怎么搞就看你自己了。比如我會加一個過期時間,一個小時過期:
export function checkAuth ()
{
var auth = JSON.parse(localStorage.getItem(STORAGE_KEY))
console.log(auth)
if(auth && auth.time){
var preTime = new Date(auth.time)
var nowTime = new Date().setHours(-1)
if(nowTime > preTime)
{
return false;
}
return auth && Object.keys(auth).length
}
else
{
return false;
}
}
VuePress 配置
在 /.vuepress 位置新增 enhanceApp.js 文件,該文件是 VuePress 對 應(yīng)用級別的配置 的配置文件,文件 export default 了一個鉤子函數(shù),并接受一個包含了一些應(yīng)用級別屬性的對象作為參數(shù)。你可以使用這個鉤子來安裝一些附加的 Vue 插件、注冊全局組件,或者增加額外的路由鉤子等
import { checkAuth } from './login/helper'
import Login from './login/Login'
export default ({
Vue,
options,
router,
siteData
}) => {
Vue.mixin({
// 請確保只在 beforeMount 或者 mounted 訪問瀏覽器 / DOM 的 API
mounted() {
const doCheck = () => {
if (!checkAuth()) {
this.$dlg.modal(Login, {
width: 400,
height: 350,
title: '請登錄您的賬號',
singletonKey: 'user-login',
maxButton: false,
closeButton: false,
callback: data => {
if (data === true) {
// do some stuff after login
}
}
})
}
}
if (this.$dlg) {
doCheck()
} else {
import('v-dialogs').then(resp => {
Vue.use(resp.default)
this.$nextTick(() => {
doCheck()
})
})
}
}
})
}
代碼中使用了 Vue.mixin 對全局進行了混入操作,所以在每個文檔頁面被訪問后都會觸發(fā)該 mounted() 生命周期進行用戶權(quán)限的校驗。在這里需要特別說明的是,原來對于權(quán)限檢查的操作,本是希望在 Vue Router 的路由守衛(wèi)中處理,但由于 瀏覽器的 API 訪問限制 原因,Vue 插件在注冊的過程中因為需要使用到瀏覽器的API (window 或 document),但在編譯為靜態(tài)文件的過程中,需要通過 Node.js 服務(wù)端渲染,因此所有的 Vue 相關(guān)代碼都應(yīng)當(dāng)遵循 編寫通用代碼 的要求。簡而言之,請確保只在 beforeMount 或者 mounted 訪問瀏覽器 / DOM 的 API
v-dialogs 在注冊的過程中需要使用到 document 這個對象,所以在編譯的過程中會出現(xiàn) document is not defined 的錯誤信息,基于上述的原因,對于功能權(quán)限的檢查在 mounted 生命周期中執(zhí)行,并將該操作進行全局混入,才能達到全局校驗的效果
上述的代碼編寫部署并重新構(gòu)建后,就會在每個文檔頁面中執(zhí)行用戶身份校驗
- 未登錄,則彈出模態(tài)窗口要求輸入身份信息進行校驗
- 已登錄時就顯示正確的文檔內(nèi)容
最終效果:
image.png
nice~~~
這樣登錄功能就好啦
評論
由于你的頁面是“靜態(tài)”的,你沒有數(shù)據(jù)庫和后端 API 的支持。但是你希望讓你的頁面擁有評論功能,讓用戶可以登錄和發(fā)表評論。 代碼托管平臺(如 Github、Gitlab、Bitbucket、Coding 等平臺,示例選擇了github)提供了 OAuth API , 在它們的幫助下,Vssue 可以讓用戶通過這些平臺的帳號登錄,將評論存儲在這些平臺的 Issue 系統(tǒng)中,并在當(dāng)前頁面展示。
評論插件:
npm install @vssue/vuepress-plugin-vssue
npm install @vssue/api-github-v3 或者 npm install @vssue/api-github-v4
使用插件
// .vuepress/config.js
module.exports = {
plugins: {
'@vssue/vuepress-plugin-vssue': {
// 設(shè)置平臺,而不是 `api`
platform: 'github-v4',
// 其他的 Vssue 配置
owner: 'OWNER_OF_REPO', // 倉庫的擁有者的名稱
repo: 'NAME_OF_REPO', // 存儲 Issue 和評論的倉庫的名稱
clientId: 'YOUR_CLIENT_ID', // 剛保存下來的 Client ID
clientSecret: 'YOUR_CLIENT_SECRET', // 剛才保存下來的 Client secrets
},
},
};
- @vssue/api-github-v3 和@vssue/api-github-v4的區(qū)別是v3不用登錄,但是有調(diào)用次數(shù)限制,v4必須登錄但沒有次數(shù)限制 v3的platform是github,v4的是github-v4 用的是github的評論功能,所以必須有g(shù)ithub賬號
如何獲取clientId和clientSecret
第一步:
登錄github后點擊 settings

第二步:點擊 Developer settings

第三步:點擊 New OAuth App

第四步:點擊注冊按鈕

這里的Client ID和Client Secret就是我們想要的了。
使用
Vssue 已經(jīng)注冊為 Vue 組件,你可以在你的 VuePress Markdown 文件中直接使用它。
<!-- README.md -->
# Vssue Demo
<Vssue/>
自動創(chuàng)建評論
但是這樣啟用的話,我們需要為每個文章手動 click to create issue 創(chuàng)建評論,這顯然不是我們需要的。
找到我們的 config.js 在插件@vssue/vuepress-plugin-vssue配置中,手動添加如下代碼:

這樣就不用我們每次去點擊 click to create issue了。
自動為每個頁面添加 Vssue
首先我們在之前下載的依賴中的 \node_modules\@vuepress路徑下的theme-default文件夾復(fù)制到.vuepress目錄下,并重命名為theme

接著我們重寫 默認主題的樣式,也就是 theme 文件夾下 layouts文件夾下的 Layout.vue組件。
找到該組件的 Page 組件部分,在插槽下方把我們的 <Vssue>組件給寫進去,即可在每個頁面都擁有評論。
這里的 :options="{ locale: 'zh' }" 意思是把地區(qū)改為中國。
由于該組件默認沒有VuePress的居中效果,我們在頁面中找了一個帶有居中效果的類 copy 過來即可居中。
最終效果:

非常nice,你也試試哇~~~
