返回
项目 Express-Mysql-Vue3-TS-Pinia 搭建菜单管理页面
前端
2023-11-07 19:56:17
导语
在创建复杂的应用程序时,通常需要一个菜单管理页面来组织和管理应用程序的不同部分。在本教程中,我们将使用 Express.js、Mysql、Vue3、Typescript 和 Pinia 来构建一个菜单管理页面。
前提条件
在继续之前,请确保你已经满足以下前提条件:
- Node.js 和 npm 已安装在你的系统上。
- 你对 Express.js、Mysql、Vue3、Typescript 和 Pinia 有基本的了解。
搭建步骤
- 创建项目
首先,创建一个新的 Node.js 项目。
mkdir express-mysql-vue3-ts-pinia-menu-management
cd express-mysql-vue3-ts-pinia-menu-management
npm init -y
- 安装依赖项
接下来,安装必要的依赖项。
npm install express mysql vue vue-router pinia typescript @types/express @types/mysql @types/vue @types/vue-router @types/pinia
- 创建数据库
现在,我们需要创建一个数据库来存储菜单数据。
mysql -u root -p
CREATE DATABASE menu_management;
- 创建数据表
接下来,我们需要在创建的数据库中创建一个数据表。
CREATE TABLE menus (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
parent_id INT,
url VARCHAR(255),
icon VARCHAR(255),
order INT,
PRIMARY KEY (id)
);
- 创建 Express.js 服务器
接下来,我们需要创建一个 Express.js 服务器。
// server.js
const express = require('express');
const app = express();
app.get('/menus', (req, res) => {
res.json([
{
id: 1,
name: 'Home',
url: '/',
icon: 'fa-home',
order: 1,
},
{
id: 2,
name: 'About',
url: '/about',
icon: 'fa-info-circle',
order: 2,
},
{
id: 3,
name: 'Contact',
url: '/contact',
icon: 'fa-envelope',
order: 3,
},
]);
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
- 创建 Vue.js 组件
接下来,我们需要创建一个 Vue.js 组件来显示菜单。
// Menu.vue
<template>
<ul>
<li v-for="menu in menus" :key="menu.id">
<a :href="menu.url">{{ menu.name }}</a>
</li>
</ul>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Menu',
data() {
return {
menus: [],
};
},
mounted() {
fetch('/menus')
.then(res => res.json())
.then(data => {
this.menus = data;
});
},
});
</script>
- 创建 Vue.js 路由
接下来,我们需要创建一个 Vue.js 路由来导航到菜单页面。
// router.js
import { createRouter, createWebHistory } from 'vue-router';
import Menu from './Menu.vue';
const routes = [
{
path: '/',
component: Menu,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
- 创建 Vue.js 应用程序
接下来,我们需要创建一个 Vue.js 应用程序。
// main.js
import { createApp } from 'vue';
import router from './router';
import Menu from './Menu.vue';
const app = createApp(Menu);
app.use(router);
app.mount('#app');
- 运行应用程序
最后,我们可以运行应用程序。
npm run dev
现在,你可以访问 http://localhost:8080 来查看菜单管理页面。