feat: 初始化 yx-nav 网址导航项目

- 技术栈: Vue3+TS+Vite + Express+SQLite
- 前台: 分类导航页、搜索、访问统计
- 后台: 仪表盘、网址CRUD、分类管理、站点配置
- 默认账号: admin / admin123
This commit is contained in:
Agent
2026-07-14 14:26:45 +08:00
commit b37140f16c
28 changed files with 5665 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# 忽略文件
node_modules/
.env
*.db
*.db-shm
*.db-wal
frontend/dist/
Binary file not shown.
Binary file not shown.
+1799
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "yx-nav-backend",
"version": "1.0.0",
"description": "网址导航后台服务",
"main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js"
},
"dependencies": {
"express": "^4.21.2",
"cors": "^2.8.5",
"bcryptjs": "^2.4.3",
"jsonwebtoken": "^9.0.2",
"better-sqlite3": "^11.8.1",
"dotenv": "^16.4.7",
"helmet": "^8.1.0",
"express-rate-limit": "^7.5.0"
},
"devDependencies": {
"nodemon": "^3.1.9"
}
}
+104
View File
@@ -0,0 +1,104 @@
import Database from 'better-sqlite3';
import bcrypt from 'bcryptjs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const dbPath = path.join(__dirname, '..', 'data', 'yx-nav.db');
const db = new Database(dbPath);
// 启用 WAL 模式和外键
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
// 初始化数据库表
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
nickname TEXT DEFAULT '管理员',
role TEXT DEFAULT 'admin',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
icon TEXT DEFAULT '🔗',
sort INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT NOT NULL,
category_id INTEGER NOT NULL,
description TEXT DEFAULT '',
icon_url TEXT DEFAULT '',
sort INTEGER DEFAULT 0,
is_show INTEGER DEFAULT 1,
views INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT UNIQUE NOT NULL,
value TEXT NOT NULL,
description TEXT DEFAULT ''
);
`);
// 初始化默认配置
const defaultSettings = {
site_name: '言逍导航',
site_description: '精心整理的网址导航',
site_logo: '',
theme_color: '#6366F1',
layout_mode: 'grid',
footer_text: '© 2026 言逍导航',
};
for (const [key, value] of Object.entries(defaultSettings)) {
db.prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)').run(key, value);
}
// 初始化默认管理员
if (!db.prepare("SELECT 1 FROM users WHERE username = 'admin'").get()) {
const hashed = bcrypt.hashSync('admin123', 10);
db.prepare("INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)").run('admin', hashed, '管理员');
}
// 初始化默认分类
if (!db.prepare("SELECT 1 FROM categories WHERE name = '常用网站'").get()) {
const cats = [
{ name: '常用网站', icon: '🌟' },
{ name: '开发工具', icon: '💻' },
{ name: '新闻资讯', icon: '📰' },
{ name: '娱乐休闲', icon: '🎮' },
{ name: '学习资源', icon: '📚' },
];
const stmt = db.prepare("INSERT INTO categories (name, icon, sort) VALUES (?, ?, ?)");
cats.forEach((c, i) => stmt.run(c.name, c.icon, i));
}
// 初始化示例链接
if (!db.prepare("SELECT 1 FROM links").get()) {
const links = [
{ title: '百度', url: 'https://www.baidu.com', desc: '全球最大的中文搜索引擎', cat: 1 },
{ title: 'GitHub', url: 'https://github.com', desc: '全球最大的代码托管平台', cat: 2 },
{ title: '掘金', url: 'https://juejin.cn', desc: '技术社区', cat: 2 },
{ title: '知乎', url: 'https://www.zhihu.com', desc: '问答社区', cat: 3 },
{ title: 'Bilibili', url: 'https://www.bilibili.com', desc: '视频网站', cat: 4 },
{ title: '慕课网', url: 'https://www.imooc.com', desc: '在线学习平台', cat: 5 },
];
const stmt = db.prepare(
"INSERT INTO links (title, url, description, category_id, sort) VALUES (?, ?, ?, ?, ?)"
);
links.forEach((l, i) => stmt.run(l.title, l.url, l.desc, l.cat, i));
}
export default db;
+35
View File
@@ -0,0 +1,35 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { fileURLToPath } from 'url';
import db from './database.js';
import apiRoutes from './routes/api.js';
import { authenticate } from './middleware/auth.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
// 安全中间件
app.use(helmet());
app.use(cors());
app.use(express.json());
// 限流
const limiter = rateLimit({ windowMs: 60_000, max: 200 });
app.use(limiter);
// 路由
apiRoutes(app);
// 健康检查
app.get('/api/health', (_req, res) => {
res.json({ status: 200, message: 'ok' });
});
app.listen(PORT, () => {
console.log(`🚀 yx-nav backend running at http://localhost:${PORT}`);
});
+27
View File
@@ -0,0 +1,27 @@
import jwt from 'jsonwebtoken';
import db from '../database.js';
const SECRET = process.env.JWT_SECRET || 'yx-nav-secret-2026';
/** JWT 认证中间件 */
export function authenticate(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ status: 401, message: '未登录' });
}
try {
const token = authHeader.slice(7);
const payload = jwt.verify(token, SECRET);
const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(payload.userId);
if (!user) return res.status(401).json({ status: 401, message: '用户不存在' });
req.user = user;
next();
} catch {
return res.status(401).json({ status: 401, message: 'Token无效' });
}
}
/** 生成 Token */
export function generateToken(userId) {
return jwt.sign({ userId }, SECRET, { expiresIn: '7d' });
}
+124
View File
@@ -0,0 +1,124 @@
import db from '../database.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { authenticate } from '../middleware/auth.js';
const SECRET = process.env.JWT_SECRET || 'yx-nav-secret-2026';
const router = (app) => {
// ---- 公开接口 ----
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body;
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user || !bcrypt.compareSync(password, user.password)) {
return res.json({ status: 401, message: '用户名或密码错误' });
}
const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '7d' });
res.json({ status: 200, message: '登录成功', result: { token, user: { id: user.id, nickname: user.nickname } } });
});
app.get('/api/site', (req, res) => {
const cats = db.prepare('SELECT * FROM categories ORDER BY sort, id').all();
const links = db.prepare('SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id WHERE l.is_show = 1 ORDER BY c.sort, l.sort, l.id').all();
const settings = {};
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
res.json({ status: 200, result: { data: { categories: cats, links, settings } } });
});
app.get('/api/site/stats', (req, res) => {
const cats = db.prepare('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id').all();
const settings = {};
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
res.json({ status: 200, result: { data: { categories: cats, settings } } });
});
app.post('/api/links/:id/view', (req, res) => {
db.prepare('UPDATE links SET views = views + 1 WHERE id = ?').run(Number(req.params.id));
res.json({ status: 200, result: { data: {} } });
});
// ---- 后台管理接口 ----
app.get('/api/admin/profile', authenticate, (req, res) => {
const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(req.user.id);
res.json({ status: 200, result: { data: user } });
});
app.put('/api/admin/profile', authenticate, (req, res) => {
db.prepare('UPDATE users SET nickname = ? WHERE id = ?').run(req.body.nickname, req.user.id);
res.json({ status: 200, message: '更新成功' });
});
app.get('/api/admin/categories', authenticate, (req, res) => {
res.json({ status: 200, result: { data: db.prepare('SELECT * FROM categories ORDER BY sort, id').all() } });
});
app.post('/api/admin/categories', authenticate, (req, res) => {
const { name, icon, sort } = req.body;
const r = db.prepare('INSERT INTO categories (name, icon, sort) VALUES (?, ?, ?)').run(name, icon || '🔗', sort || 0);
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(r.lastInsertRowid) } } });
});
app.put('/api/admin/categories/:id', authenticate, (req, res) => {
const { name, icon, sort } = req.body;
db.prepare('UPDATE categories SET name = ?, icon = ?, sort = ? WHERE id = ?').run(name, icon, sort, Number(req.params.id));
res.json({ status: 200, message: '更新成功' });
});
app.delete('/api/admin/categories/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM categories WHERE id = ?').run(Number(req.params.id));
res.json({ status: 200, message: '删除成功' });
});
app.get('/api/admin/links', authenticate, (req, res) => {
const { keyword, categoryId } = req.query;
let sql = 'SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id';
const params = [];
if (keyword) { sql += ' WHERE l.title LIKE ? OR l.description LIKE ?'; params.push(`%${keyword}%`, `%${keyword}%`); }
if (categoryId) { sql += (keyword ? ' AND' : ' WHERE') + ' l.category_id = ?'; params.push(Number(categoryId)); }
sql += ' ORDER BY l.sort, l.id';
res.json({ status: 200, result: { data: db.prepare(sql).all(...params) } });
});
app.post('/api/admin/links', authenticate, (req, res) => {
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
const r = db.prepare(
'INSERT INTO links (title, url, category_id, description, icon_url, sort, is_show) VALUES (?, ?, ?, ?, ?, ?, ?)'
).run(title, url, Number(categoryId), description || '', iconUrl || '', sort || 0, isShow !== false ? 1 : 0);
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(r.lastInsertRowid) } } });
});
app.put('/api/admin/links/:id', authenticate, (req, res) => {
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
db.prepare(
'UPDATE links SET title=?, url=?, category_id=?, description=?, icon_url=?, sort=?, is_show=? WHERE id=?'
).run(title, url, Number(categoryId), description, iconUrl, sort, isShow !== false ? 1 : 0, Number(req.params.id));
res.json({ status: 200, message: '更新成功' });
});
app.delete('/api/admin/links/:id', authenticate, (req, res) => {
db.prepare('DELETE FROM links WHERE id = ?').run(Number(req.params.id));
res.json({ status: 200, message: '删除成功' });
});
app.put('/api/admin/links/sort', authenticate, (req, res) => {
(req.body.sorts || []).forEach(({ id, sort }) => {
db.prepare('UPDATE links SET sort = ? WHERE id = ?').run(sort, Number(id));
});
res.json({ status: 200, message: '排序成功' });
});
app.get('/api/admin/settings', authenticate, (req, res) => {
const settings = {};
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
res.json({ status: 200, result: { data: settings } });
});
app.put('/api/admin/settings', authenticate, (req, res) => {
for (const [key, value] of Object.entries(req.body)) {
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?').run(key, value, value);
}
res.json({ status: 200, message: '保存成功' });
});
};
export default router;
+28
View File
@@ -0,0 +1,28 @@
import bcrypt from 'bcryptjs';
import db from '../database.js';
import { generateToken } from '../middleware/auth.js';
export const login = (req, res) => {
const { username, password } = req.body;
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user) return res.json({ status: 401, message: '用户名或密码错误' });
if (!bcrypt.compareSync(password, user.password)) {
return res.json({ status: 401, message: '用户名或密码错误' });
}
res.json({ status: 200, message: '登录成功', result: { token: generateToken(user.id), user: { id: user.id, nickname: user.nickname } } });
};
export const profile = (req, res) => {
const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(req.user.id);
res.json({ status: 200, result: { data: user } });
};
export const updateProfile = (req, res) => {
const { nickname } = req.body;
db.prepare('UPDATE users SET nickname = ? WHERE id = ?').run(nickname, req.user.id);
res.json({ status: 200, message: '更新成功' });
};
export const logout = (req, res) => {
res.json({ status: 200, message: '退出成功' });
};
+16
View File
@@ -0,0 +1,16 @@
import db from '../database.js';
export const list = (req, res) => {
const cats = db.prepare('SELECT * FROM categories ORDER BY sort, id').all();
const links = db.prepare('SELECT * FROM links WHERE is_show = 1 ORDER BY sort, id').all();
const settings = {};
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
res.json({ status: 200, result: { data: { categories: cats, links, settings } } });
};
export const listWithStats = (req, res) => {
const cats = db.prepare('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id').all();
const settings = {};
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
res.json({ status: 200, result: { data: { categories: cats, settings } } });
};
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>言逍导航</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+2510
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "yx-nav-frontend",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.5.13",
"vue-router": "^4.5.0",
"pinia": "^2.3.0",
"axios": "^1.8.4",
"element-plus": "^2.9.6",
"@element-plus/icons-vue": "^2.3.1"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.1",
"vite": "^6.2.4",
"typescript": "^5.8.0",
"vue-tsc": "^2.2.8",
"sass": "^1.85.0"
}
}
+5
View File
@@ -0,0 +1,5 @@
<template>
<router-view />
</template>
<script setup lang="ts"></script>
+56
View File
@@ -0,0 +1,56 @@
import axios from 'axios'
import { ElMessage } from 'element-plus'
export const request = axios.create({ baseURL: '/api', timeout: 10000 })
request.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
request.interceptors.response.use(
res => {
const data = res.data
if (data.status !== 200) {
ElMessage.error(data.message || '请求失败')
return Promise.reject(new Error(data.message))
}
return data
},
err => {
if (err.response?.status === 401) {
localStorage.removeItem('token')
ElMessage.error('登录已过期')
}
return Promise.reject(err)
}
)
// 前端站点 API
export const siteApi = {
getIndex: () => request.get('/site'),
addView: (id: number) => request.post(`/links/${id}/view`),
}
// 后台管理 API
export const adminApi = {
profile: () => request.get('/admin/profile'),
updateProfile: (data: any) => request.put('/admin/profile', data),
getCategories: () => request.get('/admin/categories'),
addCategory: (data: any) => request.post('/admin/categories', data),
updateCategory: (id: number, data: any) => request.put(`/admin/categories/${id}`, data),
deleteCategory: (id: number) => request.delete(`/admin/categories/${id}`),
getLinks: (params?: any) => request.get('/admin/links', { params }),
addLink: (data: any) => request.post('/admin/links', data),
updateLink: (id: number, data: any) => request.put(`/admin/links/${id}`, data),
deleteLink: (id: number) => request.delete(`/admin/links/${id}`),
updateSorts: (sorts: any[]) => request.put('/admin/links/sort', { sorts }),
getSettings: () => request.get('/admin/settings'),
updateSettings: (data: any) => request.put('/admin/settings', data),
}
// 认证 API
export const authApi = {
login: (data: any) => axios.post('/api/auth/login', data),
}
+9
View File
@@ -0,0 +1,9 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f0f2f5;
color: #333;
}
#app { min-height: 100vh; }
+13
View File
@@ -0,0 +1,13 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './assets/styles/index.scss'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')
+40
View File
@@ -0,0 +1,40 @@
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import AdminLayout from '@/views/admin/AdminLayout.vue'
import AdminDashboard from '@/views/admin/Dashboard.vue'
import AdminLinks from '@/views/admin/Links.vue'
import AdminCategories from '@/views/admin/Categories.vue'
import AdminSettings from '@/views/admin/Settings.vue'
import AdminLogin from '@/views/admin/Login.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/admin/login', name: 'login', component: AdminLogin },
{
path: '/admin',
component: AdminLayout,
redirect: '/admin/dashboard',
children: [
{ path: 'dashboard', name: 'dashboard', component: AdminDashboard },
{ path: 'links', name: 'links', component: AdminLinks },
{ path: 'categories', name: 'categories', component: AdminCategories },
{ path: 'settings', name: 'settings', component: AdminSettings },
],
},
],
})
router.beforeEach((to, _from, next) => {
const token = localStorage.getItem('token')
if (to.path.startsWith('/admin') && to.name !== 'login' && !token) {
next('/admin/login')
} else if (to.name === 'login' && token) {
next('/admin/dashboard')
} else {
next()
}
})
export default router
+33
View File
@@ -0,0 +1,33 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { adminApi } from '@/api'
import router from '@/router'
export const useUserStore = defineStore('user', () => {
const user = ref<any>(null)
const token = ref(localStorage.getItem('token') || '')
function setToken(t: string) {
token.value = t
localStorage.setItem('token', t)
}
function logout() {
token.value = ''
user.value = null
localStorage.removeItem('token')
router.push('/admin/login')
}
async function fetchProfile() {
if (!token.value) return
try {
const res = await adminApi.profile()
user.value = res.result.data
} catch {
logout()
}
}
return { user, token, setToken, logout, fetchProfile }
})
+232
View File
@@ -0,0 +1,232 @@
<template>
<div class="home">
<div class="header">
<div class="header-content">
<div class="brand">
<span class="logo">{{ data.settings.site_name || '导航' }}</span>
<p class="desc">{{ data.settings.site_description }}</p>
</div>
<el-input
v-model="search"
placeholder="搜索网址..."
class="search-box"
@input="filterLinks"
>
<template #prefix>
<el-icon><Search /></el-icon>
</template>
</el-input>
</div>
</div>
<div class="main-content">
<div
v-for="cat in filteredCategories"
:key="cat.id"
class="category-section"
>
<div class="category-header">
<span class="icon">{{ cat.icon }}</span>
<span class="name">{{ cat.name }}</span>
<span class="count">{{ linksInCat(cat.id).length }}</span>
</div>
<div class="links-grid">
<a
v-for="link in linksInCat(cat.id)"
:key="link.id"
:href="link.url"
target="_blank"
rel="noopener noreferrer"
class="link-card"
@click="handleVisit(link)"
>
<img
v-if="link.iconUrl"
:src="link.iconUrl"
:alt="link.title"
class="link-icon"
@error="onIconError($event, link)"
/>
<div v-else class="link-icon default-icon">{{ link.title[0] }}</div>
<div class="link-info">
<div class="link-title">{{ link.title }}</div>
<div class="link-desc">{{ link.description }}</div>
</div>
</a>
</div>
</div>
</div>
<footer class="footer">{{ data.settings.footer_text }}</footer>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { siteApi } from '@/api'
const data = reactive({ settings: {} as any, links: [] as any[] })
const search = ref('')
const filteredLinks = ref<any[]>([])
const filteredCategories = computed(() => {
return data.categories.filter((cat: any) =>
linksInCat(cat.id).length > 0
)
})
function linksInCat(catId: number) {
return filteredLinks.value.filter((l: any) => l.categoryId === catId)
}
function filterLinks() {
const q = search.value.trim()
filteredLinks.value = q
? data.links.filter((l: any) => l.title.toLowerCase().includes(q))
: [...data.links]
}
async function loadData() {
try {
const res = await siteApi.getIndex()
const { categories, links, settings } = res.result.data
data.categories = categories
data.links = links
data.settings = settings
filteredLinks.value = links
} catch {
ElMessage.error('加载失败')
}
}
function handleVisit(link: any) {
siteApi.addView(link.id)
}
function onIconError(e: any, link: any) {
e.target.style.display = 'none'
link.iconUrl = ''
}
loadData()
</script>
<style scoped lang="scss">
.home {
min-height: 100vh;
background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f0 100%);
}
.header {
background: white;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
position: sticky;
top: 0;
z-index: 10;
.header-content {
max-width: 1200px;
margin: 0 auto;
padding: 24px 32px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.brand {
.logo {
font-size: 28px;
font-weight: 700;
background: linear-gradient(135deg, #6366f1, #818cf8);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.desc { font-size: 14px; color: #888; margin-top: 4px; }
}
.search-box { width: 320px; }
}
.main-content {
max-width: 1200px;
margin: 0 auto;
padding: 32px;
}
.category-section { margin-bottom: 40px; }
.category-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 16px;
padding-bottom: 10px;
border-bottom: 2px solid #e5e7eb;
.icon { font-size: 20px; }
.name { font-size: 18px; font-weight: 600; }
.count {
font-size: 12px;
color: #888;
background: #f0f0f0;
padding: 2px 10px;
border-radius: 12px;
}
}
.links-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 16px;
}
.link-card {
display: flex;
align-items: center;
gap: 12px;
background: white;
padding: 16px;
border-radius: 12px;
text-decoration: none;
color: inherit;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
transition: all 0.2s;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(99,102,241,0.15);
}
.link-icon {
width: 40px;
height: 40px;
border-radius: 10px;
object-fit: cover;
flex-shrink: 0;
&.default-icon {
background: linear-gradient(135deg, #6366f1, #818cf8);
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: 16px;
}
}
.link-info { flex: 1; min-width: 0; }
.link-title { font-weight: 500; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.link-desc { font-size: 12px; color: #888; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
}
.footer {
text-align: center;
padding: 24px;
color: #aaa;
font-size: 13px;
}
</style>
+95
View File
@@ -0,0 +1,95 @@
<template>
<div class="admin-layout">
<el-aside width="200px">
<div class="sidebar-logo">言逍导航</div>
<el-menu router :default-active="$route.path">
<el-menu-item index="/admin/dashboard">
<el-icon><DataBoard /></el-icon>
<span>仪表盘</span>
</el-menu-item>
<el-menu-item index="/admin/links">
<el-icon><Link /></el-icon>
<span>网址管理</span>
</el-menu-item>
<el-menu-item index="/admin/categories">
<el-icon><Folder /></el-icon>
<span>分类管理</span>
</el-menu-item>
<el-menu-item index="/admin/settings">
<el-icon><Setting /></el-icon>
<span>站点配置</span>
</el-menu-item>
</el-menu>
</el-aside>
<el-main>
<div class="admin-header">
<el-breadcrumb separator="/">
<el-breadcrumb-item>后台管理</el-breadcrumb-item>
<el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
</el-breadcrumb>
<div class="user-area">
<span class="nickname">{{ store.user?.nickname || '管理员' }}</span>
<el-button text @click="handleLogout">退出</el-button>
</div>
</div>
<router-view />
</el-main>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { DataBoard, Link, Folder, Setting } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import router from '@/router'
const route = useRoute()
const store = useUserStore()
const titleMap: Record<string, string> = {
'/admin/dashboard': '仪表盘',
'/admin/links': '网址管理',
'/admin/categories': '分类管理',
'/admin/settings': '站点配置',
}
const pageTitle = computed(() => titleMap[route.path] || '管理')
function handleLogout() {
store.logout()
router.push('/admin/login')
}
</script>
<style scoped>
.admin-layout { height: 100vh; }
.el-aside {
background: #1e293b;
color: white;
}
.sidebar-logo {
padding: 24px;
font-size: 18px;
font-weight: 700;
text-align: center;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.el-menu {
background: transparent;
border-right: none;
}
.el-menu .el-menu-item { color: rgba(255,255,255,0.7); }
.el-menu .el-menu-item:hover { background: rgba(255,255,255,0.08); }
.el-menu .el-menu-item.is-active { background: rgba(99,102,241,0.3); color: white; }
.admin-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #e5e7eb;
}
.user-area { display: flex; align-items: center; gap: 16px; }
.nickname { color: #555; font-weight: 500; }
.el-main { background: #f5f7fa; padding: 24px; overflow-y: auto; }
</style>
+90
View File
@@ -0,0 +1,90 @@
<template>
<div class="cats-page">
<div class="page-header">
<h2>分类管理</h2>
<el-button type="primary" @click="openDialog">
<el-icon><Plus /></el-icon> 新增分类
</el-button>
</div>
<el-card>
<el-table :data="categories">
<el-table-column prop="icon" label="图标" width="80" align="center" />
<el-table-column prop="name" label="名称" />
<el-table-column prop="sort" label="排序" width="80" align="center" />
<el-table-column label="操作" width="140">
<template #default="scope">
<el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<el-dialog v-model="dialogVisible" :title="editId ? '编辑分类' : '新增分类'" width="420px">
<el-form :model="form" label-width="60px">
<el-form-item label="图标">
<el-input v-model="form.icon" placeholder="如:🌟" />
</el-form-item>
<el-form-item label="名称">
<el-input v-model="form.name" />
</el-form-item>
<el-form-item label="排序">
<el-input-number v-model="form.sort" :min="0" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="save">确定</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api'
const categories = ref([])
const dialogVisible = ref(false)
const editId = ref(null)
const form = ref({ icon: '🔗', name: '', sort: 0 })
async function load() {
categories.value = (await adminApi.getCategories()).result.data
}
function openDialog(row?: any) {
editId.value = row?.id || null
form.value = row || { icon: '🔗', name: '', sort: 0 }
dialogVisible.value = true
}
async function save() {
if (editId.value) {
await adminApi.updateCategory(editId.value, form.value)
ElMessage.success('更新成功')
} else {
await adminApi.addCategory(form.value)
ElMessage.success('创建成功')
}
dialogVisible.value = false
await load()
}
async function del(row: any) {
await ElMessageBox.confirm('确定删除此分类?')
await adminApi.deleteCategory(row.id)
ElMessage.success('删除成功')
await load()
}
onMounted(load)
</script>
<style scoped>
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-header h2 { font-size: 20px; font-weight: 600; }
</style>
+106
View File
@@ -0,0 +1,106 @@
<template>
<div class="dashboard">
<el-row :gutter="20" class="stat-cards">
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-item">
<span class="num">{{ stats.linkCount }}</span>
<span class="label">网址总数</span>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-item">
<span class="num">{{ stats.catCount }}</span>
<span class="label">分类数</span>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-item">
<span class="num">{{ stats.totalViews }}</span>
<span class="label">总访问</span>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover">
<div class="stat-item">
<span class="num">{{ settings.site_name }}</span>
<span class="label">站点名称</span>
</div>
</el-card>
</el-col>
</el-row>
<el-card style="margin-top:24px">
<template #header>
<span>快捷操作</span>
</template>
<el-row :gutter="20">
<el-col :span="6">
<el-button type="primary" block @click="$router.push('/admin/links')">
<el-icon><Plus /></el-icon> 管理网址
</el-button>
</el-col>
<el-col :span="6">
<el-button type="success" block @click="$router.push('/admin/categories')">
<el-icon><FolderAdd /></el-icon> 管理分类
</el-button>
</el-col>
<el-col :span="6">
<el-button type="warning" block @click="$router.push('/admin/settings')">
<el-icon><Setting /></el-icon> 站点配置
</el-button>
</el-col>
<el-col :span="6">
<el-button block @click="() => window.open('/', '_blank')">
<el-icon><View /></el-icon> 预览前台
</el-button>
</el-col>
</el-row>
</el-card>
<el-card style="margin-top:24px">
<template #header><span>分类概览</span></template>
<el-table :data="categories" style="width:100%">
<el-table-column prop="name" label="分类" />
<el-table-column prop="linkCount" label="网址数" width="100" />
<el-table-column prop="icon" label="图标" width="80" />
</el-table>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, FolderAdd, Setting, View } from '@element-plus/icons-vue'
import { adminApi } from '@/api'
const stats = ref({ linkCount: 0, catCount: 0, totalViews: 0 })
const settings = ref({})
const categories = ref([])
onMounted(async () => {
const [statsRes, setRes] = await Promise.all([
adminApi.getCategories(),
adminApi.getSettings()
])
categories.value = statsRes.result.data
settings.value = setRes.result.data
stats.value = {
catCount: categories.value.length,
linkCount: categories.value.reduce((s: number, c: any) => s + (c.linkCount || 0), 0),
totalViews: 0,
}
})
</script>
<style scoped>
.stat-cards { margin-bottom: 8px; }
.stat-item { text-align: center; }
.stat-item .num { display: block; font-size: 36px; font-weight: 700; color: #6366f1; margin-bottom: 8px; }
.stat-item .label { color: #888; font-size: 14px; }
</style>
+130
View File
@@ -0,0 +1,130 @@
<template>
<div class="links-page">
<div class="page-header">
<h2>网址管理</h2>
<el-button type="primary" @click="openDialog()">
<el-icon><Plus /></el-icon> 新增网址
</el-button>
</div>
<el-card>
<el-row :gutter="16" style="margin-bottom:16px">
<el-col :span="6">
<el-input v-model="keyword" placeholder="搜索标题" @input="loadLinks" />
</el-col>
<el-col :span="6">
<el-select v-model="catFilter" placeholder="选择分类" @change="loadLinks" clearable>
<el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
</el-select>
</el-col>
</el-row>
<el-table :data="links">
<el-table-column prop="title" label="标题" />
<el-table-column prop="categoryName" label="分类" width="120" />
<el-table-column prop="url" label="网址" />
<el-table-column prop="isShow" label="显示" width="80" align="center">
<template #default="scope">
<el-tag :type="scope.row.isShow ? 'success' : 'info'">
{{ scope.row.isShow ? '是' : '否' }}
</el-tag>
</template>
</el-table-column>
<el-table-column prop="views" label="访问" width="80" align="center" />
<el-table-column label="操作" width="140">
<template #default="scope">
<el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="deleteLink(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 新增/编辑弹窗 -->
<el-dialog v-model="dialogVisible" :title="editId ? '编辑网址' : '新增网址'" width="500px">
<el-form :model="form" label-width="80px">
<el-form-item label="标题">
<el-input v-model="form.title" placeholder="如:百度" />
</el-form-item>
<el-form-item label="网址">
<el-input v-model="form.url" placeholder="https://" />
</el-form-item>
<el-form-item label="分类">
<el-select v-model="form.categoryId" placeholder="选择分类">
<el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
</el-select>
</el-form-item>
<el-form-item label="图标URL">
<el-input v-model="form.iconUrl" placeholder="图标链接(可选)" />
</el-form-item>
<el-form-item label="描述">
<el-input v-model="form.description" type="textarea" placeholder="简短描述" />
</el-form-item>
<el-form-item label="排序">
<el-input-number v-model="form.sort" :min="0" />
</el-form-item>
<el-form-item label="显示">
<el-switch v-model="form.isShow" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="save">确定</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api'
const links = ref([])
const categories = ref([])
const keyword = ref('')
const catFilter = ref('')
const dialogVisible = ref(false)
const editId = ref(null)
const form = ref({ title: '', url: '', categoryId: '', description: '', iconUrl: '', sort: 0, isShow: true })
async function loadLinks() {
links.value = (await adminApi.getLinks({ keyword: keyword.value || undefined, categoryId: catFilter.value || undefined })).result.data
}
async function loadCats() {
categories.value = (await adminApi.getCategories()).result.data
}
function openDialog(row?: any) {
editId.value = row?.id || null
form.value = row || { title: '', url: '', categoryId: '', description: '', iconUrl: '', sort: 0, isShow: true }
dialogVisible.value = true
}
async function save() {
if (editId.value) {
await adminApi.updateLink(editId.value, form.value)
ElMessage.success('更新成功')
} else {
await adminApi.addLink(form.value)
ElMessage.success('创建成功')
}
dialogVisible.value = false
await loadLinks()
}
async function deleteLink(row: any) {
await ElMessageBox.confirm('确定删除?')
await adminApi.deleteLink(row.id)
ElMessage.success('删除成功')
await loadLinks()
}
onMounted(async () => { await loadLinks(); await loadCats() })
</script>
<style scoped>
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-header h2 { font-size: 20px; font-weight: 600; }
</style>
+75
View File
@@ -0,0 +1,75 @@
<template>
<div class="login-page">
<div class="login-card">
<h2>后台管理</h2>
<p class="subtitle">言逍导航</p>
<el-form @submit.prevent="handleLogin">
<el-form-item>
<el-input v-model="form.username" placeholder="用户名" size="large" autofocus>
<template #prefix><el-icon><User /></el-icon></template>
</el-input>
</el-form-item>
<el-form-item>
<el-input v-model="form.password" type="password" placeholder="密码" size="large" show-password @keyup.enter="handleLogin">
<template #prefix><el-icon><Lock /></el-icon></template>
</el-input>
</el-form-item>
<el-button type="primary" size="large" class="login-btn" @click="handleLogin" :loading="loading">登录</el-button>
</el-form>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { authApi } from '@/api'
import { useUserStore } from '@/stores/user'
const router = useRouter()
const store = useUserStore()
const loading = ref(false)
const form = ref({ username: '', password: '' })
async function handleLogin() {
if (!form.value.username || !form.value.password) {
ElMessage.warning('请输入用户名和密码')
return
}
loading.value = true
try {
const res = await authApi.login(form.value)
store.setToken(res.data.token)
await store.fetchProfile()
ElMessage.success('登录成功')
router.push('/admin/dashboard')
} catch {
ElMessage.error('用户名或密码错误')
} finally {
loading.value = false
}
}
</script>
<style scoped>
.login-page {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea, #764ba2);
}
.login-card {
background: white;
padding: 48px 40px;
border-radius: 16px;
width: 380px;
box-shadow: 0 20px 60px rgba(0,0,0,0.2);
text-align: center;
}
.login-card h2 { font-size: 24px; font-weight: 700; }
.subtitle { color: #888; margin: 8px 0 24px; }
.login-btn { width: 100%; margin-top: 8px; }
</style>
+59
View File
@@ -0,0 +1,59 @@
<template>
<div class="settings-page">
<div class="page-header"><h2>站点配置</h2></div>
<el-card>
<el-form :model="settings" label-width="120px">
<el-form-item label="站点名称">
<el-input v-model="settings.site_name" />
</el-form-item>
<el-form-item label="站点描述">
<el-input v-model="settings.site_description" />
</el-form-item>
<el-form-item label="主题色">
<el-color-picker v-model="settings.theme_color" />
</el-form-item>
<el-form-item label="布局模式">
<el-radio-group v-model="settings.layout_mode">
<el-radio value="grid">卡片网格</el-radio>
<el-radio value="list">列表</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="页脚文字">
<el-input v-model="settings.footer_text" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="save">保存配置</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminApi } from '@/api'
const settings = ref({
site_name: '',
site_description: '',
theme_color: '#6366F1',
layout_mode: 'grid',
footer_text: '',
})
onMounted(async () => {
Object.assign(settings.value, (await adminApi.getSettings()).result.data)
})
async function save() {
await adminApi.updateSettings(settings.value)
ElMessage.success('保存成功')
}
</script>
<style scoped>
.page-header { margin-bottom: 20px; }
.page-header h2 { font-size: 20px; font-weight: 600; }
</style>
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: { alias: { '@': resolve(__dirname, 'src') } },
server: { port: 5173, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true } } },
})