vue实现博客
Vue 实现博客的基本步骤
项目初始化
使用 Vue CLI 或 Vite 创建项目:
npm create vue@latest blog-project
cd blog-project
npm install
安装必要依赖
安装路由和状态管理库:
npm install vue-router pinia
项目结构设计
典型的博客项目结构:
src/
├── assets/
├── components/
│ ├── BlogPost.vue
│ ├── NavBar.vue
│ └── CommentSection.vue
├── views/
│ ├── HomeView.vue
│ ├── PostListView.vue
│ └── PostDetailView.vue
├── store/
│ └── blog.js
├── router/
│ └── index.js
└── App.vue
路由配置
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import PostListView from '../views/PostListView.vue'
import PostDetailView from '../views/PostDetailView.vue'
const routes = [
{ path: '/', component: HomeView },
{ path: '/posts', component: PostListView },
{ path: '/posts/:id', component: PostDetailView }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
状态管理
// store/blog.js
import { defineStore } from 'pinia'
export const useBlogStore = defineStore('blog', {
state: () => ({
posts: [],
currentPost: null
}),
actions: {
async fetchPosts() {
// API调用获取文章列表
},
async fetchPost(id) {
// API调用获取单篇文章
}
}
})
博客文章组件
<!-- components/BlogPost.vue -->
<template>
<div class="post">
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<div class="meta">
<span>发布于 {{ post.date }}</span>
</div>
</div>
</template>
<script setup>
defineProps({
post: {
type: Object,
required: true
}
})
</script>
实现Markdown支持
安装markdown解析器:
npm install marked
创建Markdown渲染组件:
<!-- components/MarkdownRenderer.vue -->
<template>
<div v-html="compiledMarkdown"></div>
</template>
<script setup>
import { marked } from 'marked'
import { computed } from 'vue'
const props = defineProps({
content: {
type: String,
required: true
}
})
const compiledMarkdown = computed(() => {
return marked(props.content)
})
</script>
实现评论功能
<!-- components/CommentSection.vue -->
<template>
<div class="comments">
<h3>评论</h3>
<div v-for="comment in comments" :key="comment.id">
<p>{{ comment.author }}: {{ comment.content }}</p>
</div>
<form @submit.prevent="addComment">
<input v-model="newComment" placeholder="添加评论">
<button type="submit">提交</button>
</form>
</div>
</template>
<script setup>
import { ref } from 'vue'
const comments = ref([])
const newComment = ref('')
const addComment = () => {
if (newComment.value.trim()) {
comments.value.push({
id: Date.now(),
author: '匿名用户',
content: newComment.value
})
newComment.value = ''
}
}
</script>
与后端API集成
使用axios进行API调用:
npm install axios
示例API调用:
import axios from 'axios'
const fetchPosts = async () => {
try {
const response = await axios.get('/api/posts')
return response.data
} catch (error) {
console.error('获取文章列表失败:', error)
return []
}
}
部署准备
创建生产版本:

npm run build
部署到静态网站托管服务,如Vercel、Netlify或GitHub Pages。






