Vue 3 管理后台项目搭建教程

Vue 3 管理后台项目搭建教程

本教程将引导你一步步搭建一个完整的 Vue 3 管理后台项目,包括项目初始化、路由配置、状态管理、组件开发、API 集成等。

项目初始化

步骤 1: 创建 Vue 项目

使用 Vue CLI 或者 Vite 创建一个新的 Vue 3 项目。

使用 Vue CLI:

                
npm install -g @vue/cli
vue create my-admin-project
# 选择 Vue 3 preset
                
            

或者,使用 Vite:

                
npm create vite@latest my-admin-project --template vue
                
            

进入项目目录:

           
cd my-admin-project
           
         

安装依赖:

                
npm install
# 或者
yarn install
               
             

步骤 2: 安装必要的依赖

为了构建一个完整的管理后台,我们需要安装一些常用的库:

安装 Vue Router:

                
npm install vue-router@4
# 或者
yarn add vue-router@4
               
            

安装 Pinia(状态管理):

            
npm install pinia
# 或者
yarn add pinia
           
         

安装 UI 组件库(这里选择 Element Plus):

               
npm install element-plus
# 或者
yarn add element-plus
             
          

安装 Axios (用于请求API):

                    
npm install axios
# 或者
yarn add axios
                    
                 

项目结构规划

步骤 3: 项目目录结构规划

一个典型的 Vue 3 管理后台项目目录结构如下:

                 
my-admin-project/
├── public/                # 静态资源
├── src/
│   ├── assets/           # 静态资源 (例如:图片,字体)
│   ├── components/       # 通用组件
│   ├── layouts/          # 布局组件
│   ├── router/           # 路由配置
│   │   └── index.js
│   ├── stores/           # Pinia 状态管理
│   │   └── modules/
│   ├── views/            # 页面组件
│   ├── api/              # API 请求
│   ├── utils/            # 工具函数
│   ├── App.vue           # 根组件
│   └── main.js           # 项目入口
│   └──  ...
├── ...
└── package.json
                 
             

你可以根据实际需要调整和增加目录。

核心功能实现

步骤 4: 路由配置 (src/router/index.js)

配置 Vue Router 实现页面跳转:

                
import { createRouter, createWebHistory } from 'vue-router';
import Dashboard from '../views/Dashboard.vue';
import UserList from '../views/UserList.vue';

const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
  },
  {
    path: '/users',
    name: 'Users',
    component: UserList,
  },
   // Add more routes here
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;
               
           

步骤 5: Pinia 状态管理 (src/stores/modules/user.js)

定义 user store:

                
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null,
  }),
  actions: {
    setToken(token) {
      this.token = token;
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
  },
});
               
           

步骤 6: 组件开发 (src/components/HelloWorld.vue)

创建一个简单的组件:

               
<template>
  <div class="hello">
    <h2>{{ msg }}</h2>
  </div>
</template>

<script setup>
defineProps({
    msg:{
     type: String,
     default: 'Hello World!'
    }
});

</script>
               
           

步骤 7: 使用 Element Plus

在 `main.js` 文件中引入 Element Plus:

            
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';

const app = createApp(App);
app.use(router).use(createPinia()).use(ElementPlus);
app.mount('#app');
            
         

然后在组件中使用 Element Plus 组件:

            
 <template>
  <el-button type="primary" @click="handleClick">
      点击我
   </el-button>
  </template>

  <script setup>
    import { ElMessage } from 'element-plus';
    const handleClick = () => {
        ElMessage.success('成功!')
    }
  </script>
            
            

步骤 8: API 请求封装 (src/api/user.js)

使用 Axios 封装 API 请求:

              
import axios from 'axios';

const instance = axios.create({
    baseURL: 'https://api.example.com', // 替换为你的API地址
    timeout: 10000,
});

export const getUserList = () => {
  return instance.get('/users');
};
export const login = (data) =>{
    return instance.post('/login', data)
}
              
           

步骤 9: 完整示例代码

这里将之前创建的组件组合在一起,并实现简单的页面展示

App.vue

           
<template>
  <router-view />
</template>
           
         

views/Dashboard.vue

          
<template>
   <h1>Dashboard</h1>
   <HelloWorld msg="欢迎来到后台管理系统" />
</template>
<script setup>
 import HelloWorld from '../components/HelloWorld.vue'
</script>
          
          

views/UserList.vue

           
<template>
  <h1>User List</h1>
  <el-button type="primary" @click="fetchUsers">
        获取用户列表
  </el-button>
  <ul>
    <li v-for="user in userList" :key="user.id">{{user.name}}</li>
  </ul>
</template>
<script setup>
 import { ref } from 'vue';
  import { getUserList } from '../api/user';
    const userList = ref([])
    const fetchUsers = async () => {
        try{
        const res = await getUserList();
        userList.value = res.data;
        }catch(e){
            console.log('获取用户列表失败',e);
        }
    }

</script>
           
          

启动项目

步骤 10: 启动项目

运行以下命令启动项目:

            
npm run dev
# 或者
yarn dev
           
         

然后在浏览器中访问 `http://localhost:5173`(或者其他端口)

声明:本教程提供了一个基础的管理后台项目框架,实际开发中可能需要更多的功能和优化。请根据你的实际需要进行调整。

互动区域

登录后可以点赞此内容

参与互动

登录后可以点赞和评论此内容,与作者互动交流