Vue2全栈博客开发实战:从零搭建Jackblog个人博客系统
引言:为什么选择Jackblog Vue版?
你是否还在为搭建个人博客系统而烦恼?面对众多技术栈无从下手?本文将带你从零开始,使用Vue2+Vuex+Vue Router构建一个功能完备的现代化个人博客系统——Jackblog Vue版。通过本文,你将掌握:
- 前后端分离架构下的博客系统设计思路
- Vue生态核心技术(Vue2、Vuex、Vue Router)的实战应用
- Webpack构建优化与项目部署最佳实践
- 博客核心功能(文章管理、用户认证、评论系统)的实现方案
项目概述
Jackblog是一个开源的个人博客系统,采用前后端分离架构设计。本项目为Vue客户端实现,基于Vue2生态,配合Express服务端(需单独部署),提供完整的博客功能体验。
技术栈概览
| 技术栈 | 版本 | 作用 |
|---|---|---|
| Vue | 2.4.4 | 核心前端框架 |
| Vuex | 2.4.0 | 状态管理 |
| Vue Router | 2.7.0 | 路由管理 |
| Vue Resource | 1.3.4 | HTTP客户端 |
| Webpack | 3.6.0 | 模块打包工具 |
| Express | 4.15.4 | 生产环境服务器 |
项目架构
环境搭建
前置要求
- Node.js v8.0+
- npm v5.0+
- Git
- 后端服务(Express或Koa版)
快速开始
# 克隆仓库
git clone https://link.gitcode.com/i/75627cc1b6a7e2400fe97ffbb51e394c.git
cd jackblog-vue
# 安装依赖
npm install
# 开发模式启动
npm run dev
执行上述命令后,浏览器将自动打开 http://localhost:3000,你将看到博客系统的首页。
目录结构解析
jackblog-vue/
├── src/ # 源代码目录
│ ├── api/ # API请求模块
│ ├── assets/ # 静态资源
│ ├── components/ # Vue组件
│ │ ├── Article/ # 文章相关组件
│ │ ├── Home/ # 首页组件
│ │ ├── Login/ # 登录组件
│ │ └── ...
│ ├── store/ # Vuex状态管理
│ │ ├── modules/ # 模块化store
│ │ ├── actions.js # 全局actions
│ │ └── index.js # store入口
│ ├── router.js # 路由配置
│ ├── config.js # 项目配置
│ └── index.js # 应用入口
├── webpack.config.js # Webpack配置
├── server.js # 生产服务器
└── package.json # 项目依赖
核心架构解析
路由系统设计
Jackblog Vue版采用Vue Router实现前端路由,支持历史模式(HTML5 History API),主要路由配置如下:
// src/router.js 核心代码
const router = new Router({
mode: 'history',
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/login', name: 'login', component: Login, meta: { requiresNotAuth: true } },
{ path: '/settings', name: 'settings', component: Settings, meta: { requiresAuth: true } },
{ path: '/article/:aid', name: 'article', component: Article },
{ path: '*', component: NotFound }
]
})
// 路由守卫实现权限控制
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isLogin()) {
return next({ path: '/login' })
}
}
// ...其他守卫逻辑
next()
})
路由设计遵循以下原则:
- 基于组件的懒加载,优化初始加载速度
- 使用路由元信息(meta)实现权限控制
- 404页面处理所有未匹配路由
- 路由切换时的滚动行为控制
状态管理架构
项目采用Vuex进行状态管理,采用模块化设计,将不同业务领域的状态分离:
// src/store/index.js
export default new Vuex.Store({
actions,
getters,
modules: {
apps,
articleList,
prenextArticle,
articleDetail,
auth,
commentList,
globalVal,
options,
logins,
tagList,
showmsg
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
核心状态模块说明:
| 模块名 | 作用 |
|---|---|
| auth | 用户认证相关状态 |
| articleList | 文章列表状态 |
| articleDetail | 文章详情状态 |
| commentList | 评论列表状态 |
| tagList | 标签相关状态 |
| showmsg | 全局消息提示状态 |
API请求层设计
项目采用RESTful API设计风格,封装了统一的API请求层:
// src/api/index.js 核心代码
export default {
// 用户认证
localLogin: function(data) {
return AuthResource.save({ id: 'local' }, data)
},
getMe: function() {
return UserResource.get({ id: 'me' })
},
// 文章相关
getFrontArticleList: function(options) {
return ArticleResource.get({ id: 'getFrontArticleList', ...options })
},
getFrontArticle: function(id) {
return ArticleResource.get({ id: id, controller: 'getFrontArticle' })
},
// 评论相关
getFrontCommentList: function(id) {
return CommentResource.get({ id: id, controller: 'getFrontCommentList' })
},
addNewComment: function(data) {
return CommentResource.save({ id: 'addNewComment' }, data)
}
}
API请求层使用vue-resource实现,统一处理请求/响应拦截、错误处理等。
核心功能实现
用户认证系统
用户认证基于JWT(JSON Web Token)实现,认证流程如下:
认证相关代码实现:
// src/store/modules/auth.js 核心代码
const actions = {
localLogin(store, userInfo) {
api.localLogin(userInfo).then(response => {
if (!response.ok) {
return showMsg(store, response.data.error_msg || '登录失败')
}
// 保存token到cookie
const token = response.data.token
saveCookie('token', token)
// 获取用户信息
store.dispatch('getUserInfo')
store.commit(LOGIN_SUCCESS, { token: token })
showMsg(store, '登录成功,欢迎光临!', 'success')
router.push({ path: '/' })
})
},
logout({ commit }) {
signOut()
commit(LOGOUT_USER)
window.location.pathname = '/'
}
}
文章详情功能
文章详情页是博客系统的核心功能,实现了文章展示、点赞、评论等功能:
<!-- src/components/Article/index.vue 核心代码 -->
<template>
<div class="article-box">
<ArtickeContent :article-detail="articleDetail"></ArtickeContent>
<Like :like-count="articleDetail.like_count" :is-like="articleDetail.isLike"></Like>
<Prenext :prev-article="prevArticle" :next-article="nextArticle"></Prenext>
<Comment :comment-list="commentList" :user="user"></Comment>
<Loginmodal ref='modal'></Loginmodal>
<Scrolltop></Scrolltop>
</div>
</template>
<script>
export default {
components: { ArtickeContent, Like, Prenext, Comment, Scrolltop, Loginmodal },
computed: {
...mapState({
articleDetail: ({ articleDetail }) => articleDetail.item,
user: ({ auth }) => auth.user,
nextArticle: ({ prenextArticle }) => prenextArticle.next,
prevArticle: ({ prenextArticle }) => prenextArticle.prev,
commentList: ({ commentList }) => commentList.items,
aid: ({ route }) => route.params.aid
})
},
created() {
this.initData()
},
watch: {
'$route': 'initData'
},
methods: {
...mapActions([
'getArticleDetail',
'getPrenext',
'getCommentList',
'toggleLike',
'addComment',
'addReply'
]),
initData() {
const aid = this.$route.params.aid
this.getPrenext(aid)
this.getCommentList(aid)
this.getArticleDetail(aid, this.user)
},
// 点赞功能
handleToggleLike() {
if (this.user) {
this.toggleLike(this.$route.params.aid)
}
},
// 评论功能
handleSubmitComment(content) {
if (this.user && content.trim() !== '') {
this.addComment({ aid: this.$route.params.aid, content: content })
} else {
this.openLoginModal()
}
}
}
}
</script>
文章详情组件采用了组件化设计,将内容展示、点赞、评论等拆分为独立组件,提高代码复用性和维护性。
评论系统
评论系统支持多级回复,实现了评论列表展示、添加评论、回复评论等功能:
// src/api/index.js 评论相关API
addNewComment: function(data) {
return CommentResource.save({ id: 'addNewComment' }, data)
},
addNewReply: function(id, data) {
return CommentResource.save({ id: id, controller: 'addNewReply' }, data)
},
delComment: function(id) {
return CommentResource.remove({ id: id })
},
delReply: function(id, data) {
return CommentResource.update({ id: id, controller: 'delReply' }, data)
}
开发与构建
开发环境配置
项目使用Webpack Dev Server提供开发环境支持,配置如下:
// webpack.config.js 开发环境配置
config.devServer = {
contentBase: path.join(__dirname, 'src'),
port: 3000,
host: 'localhost',
historyApiFallback: true,
inline: true,
hot: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
}
开发环境特性:
- 热模块替换(HMR),实时更新
- 错误信息提示
- 源映射(Source Map)支持调试
- 自动打开浏览器
生产环境构建
生产环境构建命令:
npm run build
构建过程主要完成以下任务:
- 代码压缩混淆(JavaScript、CSS)
- 资源优化(图片压缩、字体处理)
- 代码分割( vendor chunk 和 app chunk)
- 静态资源版本控制(hash文件名)
- HTML文件生成与注入
Webpack生产环境配置:
// webpack.config.js 生产环境配置
if (!debug) {
config.plugins.push(
new UglifyJSPlugin()
)
}
部署方案
项目提供了多种部署方式:
- 简单启动
npm run start:dist
- 使用PM2进行进程管理(推荐生产环境使用)
pm2 start process.json
process.json配置:
{
"name": "jackblog-vue",
"script": "server.js",
"instances": 2,
"exec_mode": "cluster",
"env": {
"NODE_ENV": "production",
"PORT": 8400
},
"error_file": "./logs/err.log",
"out_file": "./logs/out.log",
"merge_logs": true,
"log_date_format": "YYYY-MM-DD HH:mm:ss Z"
}
- 服务器配置
// server.js 生产服务器
var app = new express()
var port = process.env.PORT || 8400
app.use(express.static(path.join(__dirname, 'dist')))
app.use(favicon(path.join(__dirname, 'dist', 'favicon.ico')))
// 支持HTML5 History模式路由
app.get('/*', function(req, res) {
return res.sendFile(__dirname + '/dist/index.html')
})
app.listen(port, function(err) {
if (err) {
console.error(err)
} else {
console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port)
}
})
高级特性与优化
性能优化策略
- 代码分割与懒加载
// src/router.js 路由懒加载
const Home = () => import('components/Home/index')
const Login = () => import('components/Login/index')
const Settings = () => import('components/Settings/index')
const Article = () => import('components/Article/index')
- 图片优化
// webpack.config.js 图片处理
{
test: /\.(jpe?g|png|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
name: 'images/[hash:8].[name].[ext]'
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: { quality: 65 },
pngquant: { quality: '65-90', speed: 4 },
gifsicle: { optimizationLevel: 7 }
}
}
]
}
- 缓存策略
- 静态资源文件名包含hash,实现长期缓存
- 合理设置HTTP缓存头
跨域处理
开发环境跨域配置(需配合服务端CORS设置):
// src/config.js
export const API_ROOT = (process.env.NODE_ENV === 'production')
? 'https://api.jackhu.top/'
: 'http://localhost:9000/'
响应式设计
项目采用响应式设计,适配不同屏幕尺寸:
/* src/assets/styles/index.css */
@media (max-width: 768px) {
.article-container {
padding: 0 15px;
}
.sidebar {
display: none;
}
.mobile-menu {
display: block;
}
}
常见问题与解决方案
1. 开发环境启动后无法访问API
解决方案:
- 确保服务端已启动并运行在正确端口
- 检查config.js中的API_ROOT配置是否正确
- 确认服务端已配置CORS允许跨域请求
2. 构建后页面空白
解决方案:
- 检查浏览器控制台是否有JavaScript错误
- 确认部署路径与publicPath配置一致
- 检查是否正确设置了HTML5 History模式的服务器配置
3. 登录后无法保持认证状态
解决方案:
- 检查CookieDomain配置是否正确
- 确认浏览器是否阻止了Cookie
- 检查token验证逻辑是否正确
总结与展望
Jackblog Vue版作为一个成熟的开源博客系统,展示了Vue2生态在实际项目中的应用。通过本文的学习,你不仅掌握了该系统的搭建和使用,更重要的是理解了Vue项目的架构设计思想和最佳实践。
项目优势
- 前后端分离,架构清晰
- 模块化设计,易于扩展
- 丰富的功能,满足博客系统需求
- 良好的性能优化
- 完善的开发和部署流程
未来展望
-
技术栈升级
- 迁移到Vue3 + Composition API
- 使用Vite替代Webpack,提升构建速度
- 集成TypeScript,提高代码质量
-
功能增强
- 加入Markdown编辑器
- 实现文章管理后台
- 添加搜索功能
-
体验优化
- 实现PWA,支持离线访问
- 优化移动端体验
- 加入暗黑模式
学习资源
贡献指南
欢迎通过以下方式贡献项目:
- 提交Issue报告bug或建议
- 提交Pull Request修复bug或添加功能
- 改进文档
- 传播分享项目
结语
个人博客不仅是展示自我的平台,也是技术实践的绝佳项目。通过构建和定制Jackblog Vue版,你可以深入掌握现代前端技术栈,提升工程实践能力。希望本文能帮助你顺利搭建属于自己的个人博客系统!
如果觉得本文对你有帮助,请点赞、收藏、关注三连,你的支持是我持续创作的动力!下期将带来"Jackblog服务端开发实战",敬请期待!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



