在前端开发领域,Vue.js 是一个非常流行且强大的框架。本文将详细介绍如何使用 Vue3 构建一个完整的响应式个人博客网站。无论你是初学者还是有一定经验的开发者,本文都将为你提供详细的步骤和代码示例。
首先,确保你已经安装了 Node.js 和 npm。然后,全局安装 Vue CLI:
npm install -g @vue/cli
使用 Vue CLI 创建一个新的 Vue 项目:
vue create my-blog
选择默认配置或手动选择特性(推荐选择 Babel、Router 和 Vuex)。
进入项目目录并启动开发服务器:
cd my-blog
npm run serve
创建如下项目结构:
my-blog
├── public
│ └── index.html
├── src
│ ├── assets
│ ├── components
│ │ ├── Header.vue
│ │ ├── Footer.vue
│ │ ├── ArticleCard.vue
│ ├── views
│ │ ├── Home.vue
│ │ ├── Articles.vue
│ │ ├── ArticleDetail.vue
│ │ ├── About.vue
│ ├── router
│ │ └── index.js
│ ├── store
│ │ └── index.js
│ ├── App.vue
│ ├── main.js
在 src/views
目录下创建 Home.vue
文件:
欢迎来到我的博客
这是一个使用 Vue3 构建的个人博客网站。
在 src/views
目录下创建 Articles.vue
文件:
文章列表
在 src/views
目录下创建 ArticleDetail.vue
文件:
{{ article.title }}
{{ article.content }}
在 src/views
目录下创建 About.vue
文件:
关于我
我是某某某,一名热爱编程的前端开发者。
在 src/router/index.js
中配置路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Articles from '../views/Articles.vue'
import ArticleDetail from '../views/ArticleDetail.vue'
import About from '../views/About.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/articles',
name: 'Articles',
component: Articles
},
{
path: '/article/:id',
name: 'ArticleDetail',
component: ArticleDetail,
props: true
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
在 src/store/index.js
中设置 Vuex 存储:
import { createStore } from 'vuex'
export default createStore({
state: {
articles: [
{ id: 1, title: '第一篇文章', content: '这是第一篇文章的内容' },
{ id: 2, title: '第二篇文章', content: '这是第二篇文章的内容' }
]
},
mutations: {},
actions: {},
modules: {}
})
在 src/main.js
中引入 Vuex:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(store).use(router).mount('#app')
更新 Articles.vue
使用 Vuex 数据:
文章列表
keep-alive
组件来缓存页面,减少重复渲染。webpack
的代码分割功能来减小初始加载时间。将项目部署到 GitHub Pages 或其他静态站点托管服务上。以下是使用 GitHub Pages 的步骤:
gh-pages
插件:npm install gh-pages --save-dev
package.json
中添加 deploy
脚本:{
"scripts": {
"build": "vue-cli-service build",
"deploy": "gh-pages -d dist"
}
}
vue.config.js
:module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/your-repo-name/' : '/'
}
npm run build
npm run deploy
通过本文,我们从零开始构建了一个完整的响应式个人博客网站。希望这篇文章对你有所帮助!如果你有任何问题或建议,请在评论区留言。
作者:[Zllgogo]
日期:[2025.3.19]
版权声明:本文为原创文章,未经授权不得转载。