基于Vue3 + Element Plus 的后台管理系统详细教程

  1. Vue3 概述

Vue.js 是一种轻量级MVVM框架,它通过双向绑定的方式,将视图与数据进行关联,简化了前端开发的流程。Vue3 是 Vue.js 的下一个版本,与早期版本相比,它具有更高的性能和更好的开发体验。

  • Composition API

Vue 3 中最大的新特性是引入了 Composition API,它允许开发人员按照逻辑相关的方式组织代码,可以更好地复用组件和处理复杂的逻辑。

  • Teleport

Teleport 是 Vue 3 中的一个新特性,它允许开发人员将一个组件的内容渲染到应用程序 DOM 中的任何位置。这对于实现带有模态框或弹出菜单的应用程序很有用。

  1. Element Plus 概述

Element Plus 是一个基于 Vue 3 的开源 UI 组件库,它是 Element UI 的升级版。

Element Plus 提供了一些常见的组件和样式,比如表单和按钮,可以轻松地构建一个漂亮的 UI 界面。

  1. 使用 Vue3 和 Element Plus 创建后台管理系统的步骤

3.1 创建一个 Vue3 项目

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

vue create my-project

3.2 安装 Element Plus

使用 npm 或 yarn 安装 Element Plus:

yarn add element-plus

3.3 引入 Element Plus

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

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'

import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

3.4 使用组件

在组件中,使用 Element Plus 提供的组件:


3.5 创建路由

创建路由,并将路由添加到应用程序中:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

const app = createApp(App)

app.use(router)
app.mount('#app')

3.6 创建 Vuex store

创建 Vuex store:

import { createStore } from 'vuex'

const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    increment(context) {
      context.commit('increment')
    }
  },
  getters: {
    getCount(state) {
      return state.count
    }
  }
})

在组件中使用 Vuex:




以上是使用 Vue3 和 Element Plus 创建后台管理系统的基本步骤,但如果你想要实现一个实用的后台管理系统,还需要实现登录、权限管理、数据增删改查等功能。

  1. 登录和权限管理功能

4.1 搭建登录页面

在页面中创建一个登录表单


在 data 中声明登录所需参数,初始化表单验证规则并在 method 中实现表单的提交、参数的验证与登录状态的切换。

export default {
  data() {
    return {
      loginParams: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          login(this.loginParams.username, this.loginParams.password)
            .then(() => {
              this.$message.success('登录成功')
              this.$router.push('/')
            })
            .catch((error) => {
              console.error(error)
              this.$message.error('登录失败')
            })
        }
      })
    }
  },
  computed: {
    loginFormValid() {
      return this.$refs.loginForm ? this.$refs.loginForm.form.valid : true
    }
  }
}

4.2 登录状态切换

登录状态的切换可以使用 Vuex 进行管理。

在 Vuex store 中,存储当前用户的登录状态和用户信息:

const store = createStore({
  state: {
    isAuthenticated: false,
    user: null
  },
  mutations: {
    setAuthenticated(state, isAuthenticated) {
      state.isAuthenticated = isAuthenticated
    },
    setUser(state, user) {
      state.user = user
    }
  },
  actions: {
    login(context, credentials) {
      // 登录操作并设置 isAuthenticated 和 user
    },
    logout(context) {
      // 退出登录操作并重置 isAuthenticated 和 user
    }
  }
})

在 App.vue 中,使用 computed 属性监听 isAuthenticated 的变化,根据其值显示不同的导航栏内容:




在登录页面中,使用表单提交用户的登录凭证,并在成功登录后设置 isAuthenticated 和 user:




4.3 路由守卫

使用路由守卫实现登录状态的拦截和权限管理。

在路由配置中,使用 beforeEnter 守卫进行登录状态的拦截:

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home, meta: { requiresAuth: true } },
    { path: '/login', component: Login },
    { path: '/about', component: About, meta: { requiresAuth: true } }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})

在组件中,使用 beforeRouteEnter 守卫获取当前用户的权限信息:

export default {
  beforeRouteEnter(to, from, next) {
    const store = useStore()

    store.dispatch('getUserInfo').then(() => {
      if (!store.getters.hasPermission(to.meta.permission)) {
        next('/')
      } else {
        next()
      }
    })
  }
}

4.4 数据增删改查

使用 Element Plus 提供的表格、表单等组件实现数据的增删改查。

4.4.1 数据展示

使用 el-table 组件展示数据,并通过 el-pagination 组件实现分页:




4.4.2 数据添加和编辑

使用 el-dialogel-form 组件实现数据的添加和编辑:




4.5 权限管理

使用 Vuex 存储当前用户的权限信息,并在路由守卫中判断当前用户是否具有访问该页面的权限。

在 Vuex store 中,存储当前用户的权限信息:

const store = createStore({
  state: {
    permissions: []
  },
  mutations: {
    setPermissions(state, permissions) {
      state.permissions = permissions
    }
  },
  actions: {
    getUserInfo(context) {
      return getUserInfo().then((response) => {
        context.commit('setPermissions', response.data.permissions)
      })
    }
  },
  getters: {
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    }
  }
})

在路由配置中,使用 meta 属性存储当前页面所需的权限信息:

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home, meta: { requiresAuth: true, permission: 'view_home' } },
    { path: '/login', component: Login },
    { path: '/about', component: About, meta: { requiresAuth: true, permission: 'view_about' } }
  ]
})

在组件中,使用 beforeRouteEnter 守卫获取当前用户的权限信息,并判断当前用户是否具有访问该页面的权限:

export default {
  beforeRouteEnter(to, from, next) {
    const store = useStore()

    store.dispatch('getUserInfo').then(() => {
      if (!store.getters.hasPermission(to.meta.permission)) {
        next('/')
      } else {
        next()
      }
    })
  }
}

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