vue 实现blog
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'
import PostList from '../views/PostList.vue'
import PostDetail from '../views/PostDetail.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/posts', component: PostList },
{ path: '/posts/:id', component: PostDetail }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
状态管理
使用 Pinia 管理博客文章数据:
// stores/postStore.js
import { defineStore } from 'pinia'
export const usePostStore = defineStore('posts', {
state: () => ({
posts: [
{ id: 1, title: 'Vue入门', content: '...' },
{ id: 2, title: 'Pinia使用', content: '...' }
]
}),
actions: {
addPost(post) {
this.posts.push(post)
}
}
})
文章列表组件
创建 PostList.vue 组件:
<template>
<div>
<h1>文章列表</h1>
<ul>
<li v-for="post in postStore.posts" :key="post.id">
<router-link :to="`/posts/${post.id}`">{{ post.title }}</router-link>
</li>
</ul>
</div>
</template>
<script setup>
import { usePostStore } from '../stores/postStore'
const postStore = usePostStore()
</script>
文章详情组件
创建 PostDetail.vue 组件:
<template>
<div v-if="post">
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
</div>
<div v-else>
文章不存在
</div>
</template>
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { usePostStore } from '../stores/postStore'
const route = useRoute()
const postStore = usePostStore()
const post = computed(() =>
postStore.posts.find(p => p.id === Number(route.params.id))
)
</script>
添加文章功能
创建文章编辑组件:

<template>
<form @submit.prevent="handleSubmit">
<input v-model="title" placeholder="标题" required>
<textarea v-model="content" placeholder="内容" required></textarea>
<button type="submit">发布</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
import { usePostStore } from '../stores/postStore'
const title = ref('')
const content = ref('')
const postStore = usePostStore()
const handleSubmit = () => {
postStore.addPost({
id: Date.now(),
title: title.value,
content: content.value
})
title.value = ''
content.value = ''
}
</script>
样式优化
添加基础样式(建议使用 Tailwind CSS 或 SCSS):
npm install tailwindcss postcss autoprefixer
配置 tailwind.config.js:
module.exports = {
content: ['./index.html', './src//*.{vue,js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [],
}
部署准备
配置 vite.config.js 用于生产构建:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
base: '/vue-blog/'
})
构建命令:

npm run build
可选扩展功能
-
添加 Markdown 支持:
npm install marked -
实现评论功能:
// 在postStore中添加comments状态和addComment动作 -
用户认证:
npm install firebase -
数据持久化:
npm install axios
以上实现提供了基础博客系统的核心功能,可根据需求进一步扩展和完善。






