【从零开始:如何用Vue3打造响应式个人博客网站】

前言

在前端开发领域,Vue.js 是一个非常流行且强大的框架。本文将详细介绍如何使用 Vue3 构建一个完整的响应式个人博客网站。无论你是初学者还是有一定经验的开发者,本文都将为你提供详细的步骤和代码示例。


1. 环境搭建

首先,确保你已经安装了 Node.js 和 npm。然后,全局安装 Vue CLI:

npm install -g @vue/cli

2. 项目初始化

使用 Vue CLI 创建一个新的 Vue 项目:

vue create my-blog

选择默认配置或手动选择特性(推荐选择 Babel、Router 和 Vuex)。

进入项目目录并启动开发服务器:

cd my-blog
npm run serve

3. 项目结构设计

创建如下项目结构:

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

4. 创建首页

src/views 目录下创建 Home.vue 文件:






5. 创建文章列表页

src/views 目录下创建 Articles.vue 文件:






6. 创建文章详情页

src/views 目录下创建 ArticleDetail.vue 文件:






7. 创建关于页面

src/views 目录下创建 About.vue 文件:






8. 添加路由

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

9. 数据管理与状态管理

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 数据:






10. 优化与部署

优化

  • 懒加载:使用动态导入来实现组件的懒加载。
  • 缓存:使用 keep-alive 组件来缓存页面,减少重复渲染。
  • 代码分割:使用 webpack 的代码分割功能来减小初始加载时间。

部署

将项目部署到 GitHub Pages 或其他静态站点托管服务上。以下是使用 GitHub Pages 的步骤:

  1. 安装 gh-pages 插件:
npm install gh-pages --save-dev
  1. package.json 中添加 deploy 脚本:
{
  "scripts": {
    "build": "vue-cli-service build",
    "deploy": "gh-pages -d dist"
  }
}
  1. 配置 vue.config.js
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/your-repo-name/' : '/'
}
  1. 构建并部署:
npm run build
npm run deploy

总结

通过本文,我们从零开始构建了一个完整的响应式个人博客网站。希望这篇文章对你有所帮助!如果你有任何问题或建议,请在评论区留言。


作者:[Zllgogo]

日期:[2025.3.19]

版权声明:本文为原创文章,未经授权不得转载。



你可能感兴趣的:(vue.js,javascript,ecmascript)