vue博客实现
Vue博客实现步骤
项目初始化
使用Vue CLI或Vite创建项目。Vue CLI适合传统项目,Vite适合现代快速开发环境。
npm init vue@latest my-blog
# 或
npm create vite@latest my-blog --template vue
安装必要依赖如vue-router和axios:
npm install vue-router 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
})
export default router
状态管理
对于复杂状态,可使用Pinia管理博客文章数据。
// stores/post.js
import { defineStore } from 'pinia'
export const usePostStore = defineStore('post', {
state: () => ({
posts: [],
currentPost: null
}),
actions: {
async fetchPosts() {
this.posts = await axios.get('/api/posts')
}
}
})
博客列表组件
创建BlogList.vue组件展示文章列表,使用v-for渲染每篇文章标题和摘要。
<template>
<div v-for="post in posts" :key="post.id">
<h3>{{ post.title }}</h3>
<p>{{ post.excerpt }}</p>
<router-link :to="'/post/' + post.id">Read More</router-link>
</div>
</template>
<script setup>
import { usePostStore } from '@/stores/post'
const store = usePostStore()
const posts = store.posts
</script>
文章详情页
创建PostDetail.vue组件展示完整文章内容,通过路由参数获取文章ID。
<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 { usePostStore } from '@/stores/post'
const route = useRoute()
const store = usePostStore()
const post = computed(() => store.currentPost)
onMounted(() => {
store.fetchPost(route.params.id)
})
</script>
样式设计
使用CSS预处理器如SCSS或LESS编写样式,或采用UI框架如Element Plus、Vuetify快速搭建界面。
数据交互
通过axios与后端API通信,实现文章的获取、创建、更新和删除操作。
// api/post.js
import axios from 'axios'
export default {
getPosts() {
return axios.get('/api/posts')
},
createPost(data) {
return axios.post('/api/posts', data)
}
}
部署上线
构建生产环境代码并部署到服务器或静态网站托管服务。

npm run build
将生成的dist目录内容上传至服务器或Vercel、Netlify等平台。






