老师点击每个课程下面的进入班级按钮后,可以查看到选择该课程的学生信息,展示的结果出现在内容模块内,选课学生的班级信息存储在数据库中的class表中,根据我提供的代码和要求,检查各部分的代码,给出改善后的各个部分完整代码(userid为老师id,sid为学生id)
时间: 2024-12-17 09:35:35 浏览: 13
为了实现老师点击“进入班级”按钮后查看选课学生信息的功能,并且展示结果出现在内容模块内,我们需要对现有代码进行一些改进。以下是各个部分的改进后的完整代码:
### 1. 前端部分 (`TeachingCourse.vue`)
```vue
<template>
<div class="common-layout">
<el-container>
<el-aside width="130px" class="menu">
<sidermenu></sidermenu>
</el-aside>
<el-container>
<el-header>
<div class="header">
<el-input v-model="searchParams.courseName" placeholder="请输入课程名" class="input-with-select" clearable></el-input>
<el-button type="primary" @click="handleSearch">搜索</el-button>
<el-input v-model="searchParams.courseId" placeholder="请输入课程号" class="input-with-select" clearable></el-input>
<el-button type="primary" @click="handleSearch">搜索</el-button>
</div>
</el-header>
<el-main>
<!-- 显示课程列表 -->
<div v-if="courses.length > 0" class="course-list">
<el-card v-for="course in courses" :key="course.course_id" style="max-width: 480px; margin-bottom: 20px;">
<template #header>
<div class="card-header">
<span>{{ course.course_name }}</span>
</div>
</template>
<div class="text item">
<p>课程号: {{ course.course_id }}</p>
<p>学时: {{ course.class_hours }}</p>
<p>实验学时: {{ course.laboratory_times }}</p>
<p>学分: {{ course.credits }}</p>
<p>任教老师ID: {{ course.userid }}</p>
<div class="course-info">课程详情:{{ course.course_info }}</div>
</div>
<template #footer>
<el-button type="primary" @click="viewStudents(course)">进入班级</el-button>
<el-button type="primary">学情管理</el-button>
</template>
</el-card>
</div>
<div v-else>
<p>暂无课程信息</p>
</div>
<!-- 学生信息展示 -->
<div v-if="selectedCourse && selectedCourse.students.length > 0" class="students-list">
<h3>选课学生列表</h3>
<ul>
<li v-for="student in selectedCourse.students" :key="student.sid">
<p>学生ID: {{ student.sid }}</p>
<p>姓名: {{ student.name }}</p>
</li>
</ul>
</div>
<div v-else-if="selectedCourse && selectedCourse.students.length === 0">
<p>暂无选课学生</p>
</div>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { searchCoursesApi, getClassStudentsApi } from '../axios';
import sidermenu from './sidermenu.vue';
import Swal from 'sweetalert2';
const searchParams = ref({
courseName: '',
courseId: '',
userid: localStorage.getItem('userid') // 从localStorage获取userid
});
const courses = ref([]);
const originalCourses = ref([]);
const selectedCourse = ref(null);
const fetchCourses = async () => {
try {
const response = await searchCoursesApi(searchParams.value);
originalCourses.value = response || [];
courses.value = response || [];
} catch (error) {
console.error('获取课程失败:', error);
Swal.fire({
icon: 'error',
title: '获取课程失败',
text: '无法连接到服务器'
});
}
};
onMounted(fetchCourses);
const handleSearch = async () => {
try {
const response = await searchCoursesApi(searchParams.value);
if (response && response.length > 0) {
courses.value = response;
} else {
courses.value = [];
Swal.fire({
icon: 'info',
title: '课程不存在',
text: '没有找到与搜索条件匹配的课程'
});
}
} catch (error) {
console.error('搜索错误:', error);
Swal.fire({
icon: 'error',
title: '搜索失败',
text: '填写正确的课程号'
});
}
};
const viewStudents = async (course) => {
try {
const response = await getClassStudentsApi(course.course_id);
if (response.success) {
selectedCourse.value = { ...course, students: response.data };
} else {
Swal.fire({
icon: 'error',
title: '获取学生信息失败',
text: response.message
});
}
} catch (error) {
console.error('获取学生信息失败:', error);
Swal.fire({
icon: 'error',
title: '错误',
text: '获取学生信息失败'
});
}
};
</script>
<style scoped>
.menu {
border-right: 1px solid #545c64;
height: calc(100vh);
margin-right: 0;
}
.header {
height: 100%;
border-bottom: 1px solid #545c64;
padding: 0;
margin: 0;
display: flex;
align-items: center;
gap: 10px;
}
.input-with-select {
width: 200px;
}
.el-header {
padding: 0;
margin: 0;
}
.el-main {
padding: 0;
}
.el-container {
padding: 0;
}
.course-list {
margin-top: 20px;
}
.course-info {
word-wrap: break-word; /* 确保文本自动换行 */
white-space: pre-wrap; /* 保持空白符序列 */
overflow: auto; /* 超出部分显示滚动条 */
}
.students-list {
margin-top: 20px;
}
</style>
```
### 2. 后端部分 (`getClassStudentsApi.js`)
```javascript
let db = require('../db/index');
const mongoose = require('mongoose');
const ClassSchema = new mongoose.Schema({
course_id: String,
students: [
{
sid: String,
name: String,
},
],
});
const Class = mongoose.model('Class', ClassSchema);
// 获取课程的学生
app.get('/api/class-students/:courseId', async (req, res) => {
const { courseId } = req.params;
try {
const classData = await Class.findOne({ course_id: courseId });
if (classData) {
res.json({ success: true, data: classData.students });
} else {
res.json({ success: false, message: '未找到该课程的学生信息' });
}
} catch (error) {
console.error('获取学生信息失败:', error);
res.status(500).json({ success: false, message: '获取学生信息失败' });
}
});
```
### 3. 路由部分 (`router.js`)
```javascript
const express = require('express');
const router = express.Router();
const login = require('./api/login');
const register = require('./api/register');
const courseSearch = require('./api/courseSearch');
const courseAdd = require('./api/courseAdd');
const studentSearch = require('./api/studentSearch');
const classAddRouter = require('./api/classAdd');
const removeStudentFromClass = require('./api/removeStudentFromClassApi');
const getClassStudents = require('./api/classStudents');
router.post('/api/login', login.post);
router.post('/api/register', register.post);
router.post('/api/search-courses', courseSearch.searchCourses);
router.post('/api/add-course', courseAdd.addCourse);
router.post('/api/check-course-id', courseAdd.checkCourseId);
router.post('/api/studentSearch', studentSearch.studentSearchApi);
router.use('/api/classAdd', classAddRouter);
router.delete('/api/removeStudentFromClass', removeStudentFromClass);
router.get('/api/classStudents/:course_id', getClassStudents);
module.exports = router;
```
### 4. Axios 部分 (`axios.js`)
```javascript
import axios from 'axios';
const API_BASE_URL = 'http://localhost:3000';
const login = async (userid, password) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/login`, { userid, password });
return response.data;
} catch (error) {
console.error('Login error:', error);
}
};
const register = async (userid, password) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/register`, { userid, password });
return response.data;
} catch (error) {
console.error('Registration error:', error);
}
};
const searchCoursesApi = async (params) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/search-courses`, params);
return response.data;
} catch (error) {
console.error('Error searching courses:', error);
throw error;
}
};
const addCourse = async (courseData) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/add-course`, courseData);
return response.data;
} catch (error) {
console.error('Error adding course:', error);
throw error;
}
};
const checkCourseId = async (courseId) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/check-course-id`, { courseId });
return response.data.exists;
} catch (error) {
console.error('Error checking course ID:', error);
throw error;
}
};
const studentSearchApi = async (params) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/studentSearch`, params);
return response.data;
} catch (error) {
console.error('Error searching courses:', error);
throw error;
}
};
const addStudentToClassApi = async (data) => {
try {
const response = await axios.post(`${API_BASE_URL}/api/classAdd/addstudentToClass`, data);
return response.data;
} catch (error) {
console.error('Error adding student to class:', error);
throw error;
}
};
const removeStudentFromClassApi = async (data) => {
try {
const response = await axios.delete(`${API_BASE_URL}/api/removeStudentFromClass`, { data: data });
return response.data;
} catch (error) {
console.error('Error removing student from class:', error);
throw error;
}
};
const getClassStudentsApi = async (courseId) => {
try {
const response = await axios.get(`${API_BASE_URL}/api/classStudents/${courseId}`);
return response.data;
} catch (error) {
console.error('Error fetching class students:', error);
throw error;
}
};
export {
searchCoursesApi,
addCourse,
checkCourseId,
studentSearchApi,
addStudentToClassApi,
removeStudentFromClassApi,
getClassStudentsApi,
};
```
以上代码改进了前端和后端的部分,确保老师点击“进入班级”按钮后可以查看选课学生的信息,并且这些信息会展示在内容模块内。
阅读全文