vue实现博客
使用 Vue 实现博客的关键步骤
项目初始化与配置
使用 Vue CLI 或 Vite 创建项目,安装必要依赖:
npm create vue@latest vue-blog
cd vue-blog
npm install vue-router pinia axios
配置路由文件(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
})
状态管理与API交互
创建 Pinia store(src/stores/posts.js)管理博客数据:
import { defineStore } from 'pinia'
import axios from 'axios'
export const usePostsStore = defineStore('posts', {
state: () => ({
posts: [],
currentPost: null
}),
actions: {
async fetchPosts() {
const res = await axios.get('https://api.example.com/posts')
this.posts = res.data
},
async fetchPost(id) {
const res = await axios.get(`https://api.example.com/posts/${id}`)
this.currentPost = res.data
}
}
})
博客列表组件
创建BlogList.vue组件显示文章列表:
<template>
<div v-for="post in posts" :key="post.id">
<router-link :to="'/post/' + post.id">
<h3>{{ post.title }}</h3>
</router-link>
<p>{{ post.excerpt }}</p>
</div>
</template>
<script setup>
import { usePostsStore } from '../stores/posts'
import { storeToRefs } from 'pinia'
const store = usePostsStore()
const { posts } = storeToRefs(store)
store.fetchPosts()
</script>
文章详情页
创建PostDetail.vue组件显示单篇文章:
<template>
<article v-if="post">
<h1>{{ post.title }}</h1>
<div v-html="post.content"></div>
</article>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { usePostsStore } from '../stores/posts'
const route = useRoute()
const store = usePostsStore()
store.fetchPost(route.params.id)
const post = computed(() => store.currentPost)
</script>
样式与布局优化
添加基础样式(src/assets/main.css):
.blog-post {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.post-list {
display: grid;
gap: 1.5rem;
padding: 2rem;
}
部署准备
配置生产环境变量(.env.production):
VITE_API_BASE_URL=https://production-api.example.com
构建项目:
npm run build
扩展功能建议
用户认证系统
集成 Firebase Auth 或 JWT 实现登录功能:
// 在Pinia store中添加
async login(email, password) {
const res = await axios.post('/auth/login', { email, password })
localStorage.setItem('token', res.data.token)
}
评论功能
创建评论组件:
<template>
<div v-for="comment in comments" :key="comment.id">
<p>{{ comment.author }}: {{ comment.content }}</p>
</div>
</template>
Markdown支持
安装marked库解析Markdown内容:
npm install marked
使用示例:
import { marked } from 'marked'
const htmlContent = marked(markdownText)






