利用利用vue3+ts实现管理后台(增删改查)实现管理后台(增删改查)
简单的管理后台基本上就是数据的增删改查。主要就是 列表 + form 表单。每个页面的逻辑基本上都相同。不同的地方就是每
个页面需要调用的具体 API 及参数。
以前 vue2 的时候最简单的做法是写出来一个页面的逻辑,然后直接 copy 到各个页面中,修改 API 及参数即可。高级一点的
是利用 mixin 函数,将可复用逻辑抽离,每个页面引入 mixin。
vue3 之后新增了composition API。本文就是利用composition API,将可复用的逻辑抽离到composition API中,并引入ts,实
现一个简单的管理后台功能。
利用利用@vue/cli创建项目创建项目
首先需要将 @vue/cli 升级到最新版。本文用的是4.5.6版本。
vue create admin
cd admin
npm run serve
create选择手动选择Manually select features,会有一些交互性的选择,是否要安装router、vuex等选项,空格可以切换是否
选中。我们选中TypeScript、Router、Vuex、CSS Pre-processors。
我们利用axios + axios-mock-adapter + mockjs来进行接口请求、接口模拟及假数据生成,接下来再安装这几个包。
npm install axios
npm install -D axios-mock-adapter mockjs
项目整体框架项目整体框架
假设我们的项目包含一个 Header,Header 的作用是切换页面。两个页面,分别为 List 和 About,这两个页面都是简单的列表
+增删改查的操作。
路由路由
需要在 router 中增加一个 list 的路由信息。
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: () => { return import(/* webpackChunkName: "about" */ '../views/About.vue'); },
},
{
path: '/list',
name: 'List',
component: () => { return import(/* webpackChunkName: "list" */ '../views/List.vue'); },
},
];
列表页列表页
首先把列表页的结构写出来,List 和 About 的结构大体相似。
<template>
<div class='content_page'>
<div class='content_body'>
<div class='content_button'>
<button class='add primary' @click='addItem' title='添加'>添加</button>
</div>
<div class='content_table'>
<table>
<thead>
<tr>
<th v-for='item in thead' :key='item'>{{item}}</th>
</tr>
</thead>
<tbody>