一个完整的网站都是有前台和管理后台组成的,前台用来给真正的用户浏览和使用,后台用来给管理员管理网站内容,配置各种功能和数据等。博客的管理后台就是用来承载创建博客,发布博客,查看留言,管理博客用户这些功能的子系统。
大家好,我是落霞孤鹜
,上一篇我们已经实现了管理后台的后端接口部分,这一章我们开始搭建博客的管理后台的前端,实现对博客网站的管理功能。
一、前端界面开发
一个管理后台的功能,一般都需要从最基础的业务对象的管理开始,在我们的博客网站上,业务对象间的依赖依次是用户、标签、分类、文章、评论、点赞、留言、首页统计。
基于这个依赖关系,我们的后台管理功能也按照这样的逻辑顺序进行构建。然后在构建每一个业务对象的管理页面时,按照Type
、API
、Component
、View
、Route
顺序进行组织和代码编写。
在src/views
下创建两个文件夹admin
和client
,并把上一个章节中创建的Login.vue
移动到admin
文件夹,把Home.vue
文件移动到client
下。
1.1 菜单管理
1.1.1 Admin.vue
管理后台的功能需要一个独立的菜单导航功能,因此在src/views/admin
下新增Admin.vue
文件,用于完成左侧的菜单导航,代码如下:
<template>
<div class="body">
<div class="menu">
<el-menu :default-active="state.activePath" :router="true">
<el-menu-item index="AdminDashboard" route="/admin/dashboard"><i class="el-icon-s-home"></i> Dashboard
</el-menu-item>
<el-menu-item index="ArticleManagement" route="/admin/article"><i class="el-icon-s-order"></i> 文章
</el-menu-item>
<el-menu-item index="TagManagement" route="/admin/tag"><i class="el-icon-collection-tag"></i> 标签</el-menu-item>
<el-menu-item index="CommentManagement" route="/admin/comment"><i class="el-icon-chat-line-round"></i> 评论
</el-menu-item>
<el-menu-item index="UserManagement" route="/admin/user"><i class="el-icon-user"></i> 用户</el-menu-item>
</el-menu>
</div>
<div class="view">
<router-view/>
</div>
</div>
</template>
<script>
import {defineComponent, reactive} from "vue";
import {useRoute} from "vue-router";
export default defineComponent({
name: "Admin",
setup() {
const state = reactive({
activePath: '',
});
const route = useRoute()
if (route.name === 'Dashboard') {
state.activePath = 'AdminDashboard'
} else {
state.activePath = route.name;
}
return {
state,
}
},
});
</script>
<style lang="less" scoped>
.body {
width: 100%;
height: 100%;
box-sizing: border-box;
display: flex;
}
.user {
font-size: 20px;
}
.menu {
width: 200px;
}
.view {
width: calc(100% - 200px);
padding: 24px;
}
.el-menu {
height: 100%;
}
</style>
3.1.2 Dashboard.vue
为了接下来的开发能很好的开展,我们先处理管理后台的默认页面Dashboard
, 在src/views/admin
下创建文件Dashboard.vue
,编写代码:
<template>
<h3>Dashboard</h3>
</template>
<script lang="ts">
import { defineComponent, reactive } from "vue";
export default defineComponent({
name: 'Dashboard',
})
</script>
3.1.3 添加路由
在src/router/index.ts
下调整代码如下:
import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import Home from "../views/client/Home.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home,
meta: {}
},
{
path: "/login/",
name: "Login",
component: () =>
import("../views/admin/Login.vue")
},
{
path: '/admin',
name: 'Admin',
component: () => import("../views/admin/Admin.vue"),
children: [
{
path: '/admin/',
name: 'Dashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
{
path: '/admin/dashboard',
name: 'AdminDashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
]
},
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
export default router;
1.2 用户管理
1.2.1 Type
层
在我们处理登录和注册的时候,已经完成了用户的类型定义,也即User
的interface定义,这里增加所有返回结果的定义,用于管理接口返回的数据结构。在src/types/index.ts
文件中代码如下:
export interface User {
id: number,
username: string,
email: string,
avatar: string | any,
nickname: string | any,
is_active?: any,
is_superuser?: boolean,
created_at?: string,
}
export interface ResponseData {
count: number;
results?: any;
detail?: string;
}
1.2.2 API
层
这里要编写用户管理相关的接口,列表查询、启用、禁用、详情查看。在src/api/service.ts
编写如下代码:
import { User, ResponseData } from "../types"
export function getUserDetail(userId: number) {
return request({
url: '/user/' + userId + '/',
method: 'get',
}) as unknown as User
}
export function saveUser(method: string, data: User) {
// @ts-ignore
return request({
url: '/user/' + data.id + '/',
method,
data,
}) as unknown as ResponseData
}
1.2.3 Component
层
在查看用户详情时,我们需要一个抽屉,展示用户的详细信息,因此在src/components
下创建文件UserDetail.vue
,编写代码如下:
<template>
<el-drawer
v-model="state.visible"
:before-close="handleClose"
direction="rtl"
size="500px"
title="用户详情"
@opened="handleSearch"
>
<el-descriptions :column="1" border class="detail" >
<el-descriptions-item label="用户名">{{ state.user.username }}</el-descriptions-item>
<el-descriptions-item label="角色">{{ state.user.role }}</el-descriptions-item>
<el-descriptions-item label="状态">{{ state.user.is_active }}</el-descriptions-item>
<el-descriptions-item label="邮箱">{{ state.user.email }}</el-descriptions-item>
<el-descriptions-item label="创建时间">{{ state.user.created_at }}</el-descriptions-item>
<el-descriptions-item label="最后登录时间">{{ state.user.last_login }}</el-descriptions-item>
</el-descriptions>
</el-drawer>
</template>
<script lang="ts">
import {defineComponent, reactive} from "vue";
import {User} from "../types";
import {getUserDetail} from "../api/service";
export default defineComponent({
name: "UserDetail",
props: {
visible: {
type: Boolean,
require: true,
},
userId: {
type: Number,
require: true,
},
loading: {
type: Boolean,
require: true,
}
},
emits: ["close",],
watch: {
'$props.visible': {
async handler(val: Boolean, oldVal: Boolean) {
if (val !== oldVal) {
this.state.visible = val
}
}
}
},
setup(props) {
const state = reactive({
visible: props.visible as Boolean,
user: {} as User,
});
return {
state,
}
},
methods: {
handleClose(isOk: Boolean) {
this.$emit("close", {
user: this.state.user,
isOk,
})
},
async handleSearch() {
this.state.user = await getUserDetail(this.$props.userId)
}
}
})
</script>
<style scoped>
.detail {
padding: 24px;
margin-top: -12px;
border-top: #eeeeee 1px solid;
}
</style>
1.2.4 View
层
在用户管理中,我们通过一个表格,分页展示所有的用户信息,并通过表格的操作列,提供查看详情、启用、禁用功能。
在src/utils/index.ts
下增加方法timestampToTime
export function timestampToTime(timestamp: Date | any, dayMinSecFlag: boolean) { const date = new Date(timestamp); const Y = date.getFullYear() + "-"; const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"; const D = date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " "; const h = date.getHours() < 10 ? "0" + date.getHours() + ":" : date.getHours() + ":"; const m = date.getMinutes() < 10 ? "0" + date.getMinutes() + ":" : date.getMinutes() + ":"; const s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); if (!dayMinSecFlag) { return Y + M + D; } return Y + M + D + h + m + s;}
在src/views/admin
下新增文件User.vue
,引用UserDetail
组件,具体代码如下:
<template>
<div>
<div>
<el-form :inline="true" :model="state.params" class="demo-form-inline">
<el-form-item label="名称">
<el-input v-model="state.params.name" placeholder="账号"/>
</el-form-item>
<el-form-item label="状态">
<el-select v-model="state.params.is_active" placeholder="请选择">
<el-option :value="1" label="生效"/>
<el-option :value="0" label="禁用"/>
</el-select>
</el-form-item>
<el-form-item>
<el-button :loading="state.isLoading" type="primary" @click="handleSearch">查询</el-button>
</el-form-item>
</el-form>
</div>
<div>
<el-table ref="userTable" :data="state.userList" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
stripe>
<el-table-column type="selection" width="55"/>
<el-table-column label="ID" prop="id" width="80"/>
<el-table-column label="账号" prop="username" width="200"/>
<el-table-column label="昵称" prop="nickname" width="200"/>
<el-table-column label="状态" prop="is_active"/>
<el-table-column :formatter="datetimeFormatter" label="注册时间" prop="created_at"/>
<el-table-column label="操作">
<template #default="scope">
<el-popconfirm v-if="scope.row.is_active" cancelButtonText='取消' confirmButtonText='禁用' icon="el-icon-info"
iconColor="red" title="确定禁用该用户吗?" @confirm="disableUser(scope.$index,scope.row)">
<template #reference>
<el-button size="small" type="text">
禁用
</el-button>
</template>
</el-popconfirm>
<el-button v-if="!scope.row.is_active" size="small" type="text"
@click.native.prevent="enableUser(scope.$index, scope.row)">
启用
</el-button>
<el-button size="small" type="text"
@click.native.prevent="showUserDetail(scope.row)">
详情
</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="pagination">
<el-pagination :page-size="10" :total="state.total" background
layout="prev, pager, next"></el-pagination>
</div>
</div>
<UserDetail
:user-id="state.userId"
:visible="state.showDialog"
@close="state.showDialog = false"
/>
</template>
<script lang="ts">
import {defineComponent, reactive} from "vue";
import {ResponseData, User} from "../../types";
import {ElMessage} from "element-plus";
import {timestampToTime} from "../../utils";
import {getUserList, saveUser} from "../../api/service";
import UserDetail from "../../components/UserDetail.vue";
export default defineComponent({
name: "User",
components: {UserDetail},
setup: function () {
const state = reactive({
userList: [] as Array<User>,
params: {
name: '',
role: 'Reader',
is_active: undefined,
page: 1,
page_size: 10,
},
isLoading: false,
total: 0,
showDialog: false,
userId: 0,
saveLoading: false,
});
const handleSearch = async (): Promise<void> => {
state.isLoading = true;
try {
const data: ResponseData = await getUserList(state.params);
state.isLoading = false;
state.userList = data.results;
state.total = data.count
} catch (e) {
console.error(e)
state.isLoading = false;
}
};
const disableUser = async (index: number, row: User) => {
await saveUser('patch', {id: row.id, is_active: false} as User);
ElMessage({
message: "禁用成功!",
type: "success",
});
await handleSearch()
}
const enableUser = async (index: number, row: User) => {
await saveUser('patch', {id: row.id, is_active: true} as User);
ElMessage({
message: "启用成功!",
type: "success",
});
await handleSearch()
}
const datetimeFormatter = (row: User, column: number, cellValue: string, index: number) => {
return timestampToTime(cellValue, true);
}
handleSearch()
return {
state,
handleSearch,
datetimeFormatter,
disableUser,
enableUser,
}
},
methods: {
showUserDetail(row: User) {
this.state.userId = row.id
this.state.showDialog = true;
},
}
})
</script>
<style scoped>
.pagination {
text-align: right;
margin-top: 12px;
}
</style>
1.2.5 Router
层
有了一个新的页面,我们需要定义route
来完成路由跳转。在src/route/index.ts
文件中编写如下代码:
import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import Home from "../views/client/Home.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home,
meta: {}
},
{
path: "/login/",
name: "Login",
component: () =>
import("../views/admin/Login.vue")
},
{
path: '/admin',
name: 'Admin',
component: () => import("../views/admin/Admin.vue"),
children: [
{
path: '/admin/',
name: 'Dashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
{
path: '/admin/dashboard',
name: 'AdminDashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
{
path: '/admin/user',
name: 'UserManagement',
component: () => import("../views/admin/User.vue"),
},
]
},
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
export default router;
1.3 标签管理
主要是为了方便灵活的给文章标记类型,所以才有标签管理,标签的属性很简单,就是一个名称。
1.3.1 Type
层
在src/types/index.ts
文件中增加代码如下:
export interface Tag {
id: number,
name: string,
created_at: string,
modified_at: string,
}
export interface TagList {
count: number,
results: Array<Tag> | any
}
1.3.2 API
层
这里要编写标签管理相关的接口,列表查询、新增、修改、删除。在src/api/service.ts
编写如下代码:
export function getTagList(params: any) {
return request({
url: '/tag/',
method: 'get',
params,
}) as unknown as TagList
}
export function saveTag(method: string, data: Tag) {
let url = '/tag/'
if (['put', 'patch'].includes(method)) {
url += data.id + '/'
}
// @ts-ignore
return request({
url,
method,
data,
}) as unknown as ResponseData
}
export function addTag(data: Tag) {
return request({
url: '/tag/',
method: 'post',
data,
}) as unknown as ResponseData
}
export function deleteTag(id: number) {
return request({
url: '/tag/' + id + '/',
method: 'delete',
}) as unknown as ResponseData
}
1.3.3 Component
层
提供一个新增和修改标签的弹框组件,因此在src/components
下创建文件TagEditDialog.vue
,编写代码如下:
<template>
<el-dialog v-model="state.visible" :title="state.title" @close="handleClose(false)" width="440px" >
<el-form size="medium" label-suffix=":" class="form">
<el-form-item label="名称" label-width="80px">
<el-input v-model="state.name" autocomplete="off" size=""></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="handleClose(false)">取 消</el-button>
<el-button :loading="loading" type="primary" @click="handleClose(true)">确 定</el-button>
</span>
</template>
</el-dialog>
</template>
<script lang="ts">
import {defineComponent, PropType, reactive} from "vue";
import {Tag} from "../types";
export default defineComponent({
name: "TagEditDialog",
props: {
visible: {
type: Boolean,
require: true,
},
tag: {
type: Object as PropType<Tag>,
require: true,
},
loading: {
type: Boolean,
require: true,
}
},
emits: ["close",],
watch: {
'$props.visible': {
handler(val: Boolean, oldVal: Boolean) {
if (val !== oldVal) {
this.state.visible = val
}
if (val) {
this.state.name = this.$props.tag.name
this.state.title = this.$props.tag.id ? '修改标签' : '新增标签'
}
}
}
},
setup(props) {
const state = reactive({
visible: props.visible as Boolean,
//@ts-ignore
name: '',
//@ts-ignore
title: ''
});
return {
state,
}
},
methods: {
handleClose(isOk: Boolean) {
this.$emit("close", {
obj: {
//@ts-ignore
id: this.$props.tag.id,
name: this.state.name
},
isOk,
})
}
}
})
</script>
<style scoped>
.form{
padding-right: 24px;
}
</style>
1.3.4 View
层
通过表格管理标签,实现对标签的新增,修改,删除和列表查看,在src/views/admin
下新增文件Tag.vue
文件,编写如下代码:
<template>
<div>
<div>
<el-form :inline="true" :model="state.params" class="demo-form-inline">
<el-form-item label="名称">
<el-input v-model="state.params.name" placeholder="名称" />
</el-form-item>
<el-form-item>
<el-button
:loading="state.isLoading"
type="primary"
@click="handleSearch"
>查询</el-button
>
</el-form-item>
</el-form>
</div>
<div class="button-container">
<el-button
:loading="state.isLoading"
type="primary"
@click="showAddDialog"
><i class="el-icon-plus" /> 新 增
</el-button>
</div>
<div>
<el-table
ref="tagTable"
:data="state.tagList"
:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
stripe
>
<el-table-column type="selection" width="55" />
<el-table-column label="ID" prop="id" width="80" />
<el-table-column label="名称" prop="name" width="200" />
<el-table-column
:formatter="datetimeFormatter"
label="修改时间"
prop="modified_at"
/>
<el-table-column fixed="right" label="操作" width="120">
<template #default="scope">
<el-popconfirm
cancelButtonText="取消"
confirmButtonText="删除"
icon="el-icon-info"
iconColor="red"
title="确定删除系列吗?"
@confirm="deleteObject(scope.$index, scope.row)"
>
<template #reference>
<el-button size="small" type="text"> 删除 </el-button>
</template>
</el-popconfirm>
<el-button
size="small"
type="text"
@click.prevent="showEditDialog(scope.$index, scope.row)"
>
编辑
</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="pagination">
<el-pagination
:page-size="10"
:total="state.total"
background
layout="prev, pager, next"
></el-pagination>
</div>
</div>
<TagEditDialog
:loading="state.saveLoading"
:tag="state.tag"
:visible="state.showDialog"
@close="handleCloseDialog"
/>
</template>
<script lang="ts">
import { defineComponent, reactive } from "vue";
import { ResponseData, Tag } from "../../types";
import { addTag, deleteTag, getTagList, saveTag } from "../../api/service";
import { timestampToTime } from "../../utils";
import { ElMessage } from "element-plus";
import TagEditDialog from "../../components/TagEditDialog.vue";
import { useRoute } from "vue-router";
export default defineComponent({
name: "Tag",
components: { TagEditDialog },
watch: {
"$route.path": {
handler(val, oldVal) {
if (val !== oldVal && ["/admin/tag"].includes(val)) this.handleSearch();
},
deep: true,
},
},
setup: function () {
const route = useRoute();
const state = reactive({
tagList: [] as Array<Tag>,
params: {
name: undefined,
page: 1,
page_size: 10,
},
isLoading: false,
total: 0,
showDialog: false,
tag: {
id: 0,
name: "",
} as Tag,
saveLoading: false,
});
const handleSearch = async (): Promise<void> => {
state.isLoading = true;
try {
const data: ResponseData = await getTagList(state.params);
state.isLoading = false;
state.tagList = data.results;
state.total = data.count;
} catch (e) {
console.error(e);
state.isLoading = false;
}
};
const deleteObject = async (index: number, row: Tag) => {
await deleteTag(row.id);
ElMessage({
message: "删除成功!",
type: "success",
});
await handleSearch();
};
const datetimeFormatter = (
row: Tag,
column: number,
cellValue: string,
index: number
) => {
return timestampToTime(cellValue, true);
};
handleSearch();
return {
state,
handleSearch,
datetimeFormatter,
deleteObject,
};
},
methods: {
showEditDialog(index: number, row: Tag) {
this.state.tag = row;
this.state.showDialog = true;
},
showAddDialog() {
this.state.tag = {} as Tag;
this.state.showDialog = true;
},
async handleCloseDialog(params: any) {
if (!params.isOk) {
this.state.showDialog = false;
return;
}
this.state.saveLoading = true;
const method = this.state.tag.id ? "put" : "post";
try {
await saveTag(method, params.obj);
this.state.showDialog = false;
this.state.saveLoading = false;
await this.handleSearch();
} catch (e) {
console.error(e);
this.state.saveLoading = false;
}
},
},
});
</script>
<style scoped>
.pagination {
text-align: right;
margin-top: 12px;
}
</style>
1.3.5Router
层
定义route
来完成路由跳转。在src/route/index.ts
文件中新增代码:
import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import Home from "../views/client/Home.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home,
meta: {}
},
{
path: "/login/",
name: "Login",
component: () =>
import"../views/admin/Login.vue")
},
{
path: '/admin',
name: 'Admin',
component: () => import("../views/admin/Admin.vue"),
children: [
{
path: '/admin/',
name: 'Dashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
{
path: '/admin/dashboard',
name: 'AdminDashboard',
component: () => import("../views/admin/Dashboard.vue"),
},
{
path: '/admin/user',
name: 'UserManagement',
component: () => import("../views/admin/User.vue"),
},
{
path: '/admin/tag',
name: 'Tag',
component: () => import("../views/admin/Tag.vue"),
},
]
},
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
export default router;