vue实现个人博客
Vue 实现个人博客的步骤
项目初始化与基础配置
使用 Vue CLI 或 Vite 创建项目,安装基础依赖:
npm init vue@latest vue-blog
cd vue-blog
npm install
安装路由和状态管理库:
npm install vue-router pinia
路由配置
在 src/router/index.js 中配置路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/post/:id', component: () => import('../views/PostDetail.vue') }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
文章列表与详情页实现
创建文章列表组件 src/components/PostList.vue:
<template>
<div v-for="post in posts" :key="post.id">
<h3 @click="navigateToPost(post.id)">{{ post.title }}</h3>
<p>{{ post.excerpt }}</p>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const posts = [
{ id: 1, title: 'Vue入门', excerpt: '学习Vue基础知识' },
{ id: 2, title: 'Pinia使用', excerpt: '状态管理解决方案' }
]
const navigateToPost = (id) => {
router.push(`/post/${id}`)
}
</script>
状态管理
使用 Pinia 管理全局状态,创建 src/stores/blog.js:
import { defineStore } from 'pinia'
export const useBlogStore = defineStore('blog', {
state: () => ({
posts: [],
currentPost: null
}),
actions: {
async fetchPosts() {
// 这里可以替换为API调用
this.posts = [
{ id: 1, title: 'Vue入门', content: '...' },
{ id: 2, title: 'Pinia使用', content: '...' }
]
}
}
})
样式与布局
添加基础样式文件 src/assets/main.css:
body {
font-family: 'Arial', sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
部署准备
配置 vite.config.js 用于生产环境构建:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
base: '/blog/'
})
进阶功能扩展
- 添加Markdown支持:
npm install marked highlight.js创建Markdown渲染组件
src/components/MarkdownRenderer.vue:<template> <div v-html="compiledMarkdown"></div> </template>
marked.setOptions({ highlight: (code) => hljs.highlightAuto(code).value })
const props = defineProps(['content']) const compiledMarkdown = computed(() => marked(props.content))
```-
实现评论功能:
npm install firebase配置Firebase实时数据库存储和显示评论。
-
添加SEO优化:
npm install vue-meta在入口文件中配置:
import { createMetaManager } from 'vue-meta'
app.use(createMetaManager())
#### 项目结构建议
src/ ├── assets/ ├── components/ │ ├── PostList.vue │ └── MarkdownRenderer.vue ├── stores/ │ └── blog.js ├── views/ │ ├── Home.vue │ └── PostDetail.vue ├── router/ │ └── index.js └── App.vue

#### 部署选项
1. 静态托管服务:
- Netlify
- Vercel
- GitHub Pages
2. 服务器部署:
- 构建生产版本:`npm run build`
- 上传 `dist` 目录到服务器
3. Docker部署:
创建 `Dockerfile`:
```dockerfile
FROM node:16 as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build-stage /app/dist /usr/share/nginx/html






