Files
DecomEval/web/src/features/admin/UsersView.vue
T

72 lines
2.4 KiB
Vue

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { NButton, NDataTable, NInput, NModal, NSelect } from "naive-ui";
import Shell from "../../shell/Shell.vue";
import { api } from "../../shared/http";
interface User { id: number; username: string; role: string }
const users = ref<User[]>([]);
const show = ref(false);
const username = ref("");
const password = ref("");
const role = ref("user");
const errorText = ref("");
const columns = [
{ title: "账号", key: "username" },
{ title: "角色", key: "roleLabel" },
];
async function load() {
const result = await api<{ users: User[] }>("/api/admin/users");
users.value = result.users.map((item) => ({ ...item, roleLabel: item.role === "admin" ? "管理员" : "用户" }));
}
async function create() {
errorText.value = "";
try {
await api("/api/admin/users", { method: "POST", body: JSON.stringify({ username: username.value, password: password.value, role: role.value }) });
show.value = false;
username.value = "";
password.value = "";
await load();
} catch (error) {
errorText.value = error instanceof Error ? error.message : "添加失败";
return false;
}
}
async function remove(id: number) {
await api(`/api/admin/users/${id}`, { method: "DELETE" });
await load();
}
onMounted(load);
</script>
<template>
<Shell>
<header class="topbar">
<h1>用户</h1>
<n-button type="primary" @click="show = true">添加用户</n-button>
</header>
<div class="content">
<n-data-table :columns="columns" :data="users" :bordered="false" />
<div v-for="user in users" :key="user.id" class="row-actions" style="margin-top: 8px">
<span>{{ user.username }}</span>
<n-button size="small" @click="remove(user.id)">删除</n-button>
</div>
</div>
<n-modal v-model:show="show" preset="dialog" title="添加用户" positive-text="保存" negative-text="取消" @positive-click="create">
<div class="form-grid">
<label>账号</label>
<n-input v-model:value="username" />
<label>密码</label>
<n-input v-model:value="password" type="password" />
<label>角色</label>
<n-select v-model:value="role" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" />
</div>
<p v-if="errorText" style="color: var(--danger)">{{ errorText }}</p>
</n-modal>
</Shell>
</template>