frontend/src/components/CreateEditCourseModel.vue
2024-07-04 21:21:59 +08:00

123 lines
3.4 KiB
Vue

<template>
<div class="modal">
<div class="modal-content">
<h3>{{ course ? '编辑课程' : '新增课程' }}</h3>
<form @submit.prevent="submitForm">
<input v-model="form.name" placeholder="课程名称" required>
<textarea v-model="form.description" placeholder="课程简介" required></textarea>
<input v-model="form.author" placeholder="课程作者" required>
<input v-model="form.sortOrder" type="number" placeholder="课程排序" required>
<h2>上传封面图片</h2>
<input type="file" @change="handleFileChange">
<img v-if="imageUrl" :src="imageUrl" alt="Image preview" width="200" />
<h2>上传视频</h2>
<input type="file" @change="handleVideoChange">
<video v-if="videoUrl" :src="videoUrl" controls width="400"></video>
<button type="submit">确定</button>
<button @click="$emit('close')">取消</button>
</form>
</div>
</div>
</template>
<script>
import CourseService from '@/services/courseService';
export default {
props: ['course'],
data() {
return {
form: {
name: '',
description: '',
author: '',
sortOrder: '',
coverImage: null,
video: null
},
imageUrl: null,
videoUrl: null,
};
},
methods: {
handleFileChange(event) {
const file = event.target.files[0];
if (file) {
this.form.coverImage = file;
this.imageUrl = URL.createObjectURL(file);
}
},
handleVideoChange(event) {
const file = event.target.files[0];
if (file) {
this.form.video = file;
this.videoUrl = URL.createObjectURL(file);
}
},
submitForm() {
const formData = new FormData();
formData.append('name', this.form.name);
formData.append('description', this.form.description);
formData.append('author', this.form.author);
formData.append('sortOrder', this.form.sortOrder);
formData.append('coverImage', this.form.coverImage);
formData.append('video', this.form.video);
if (this.course) {
CourseService.editCourse(this.course.id, formData)
.then(() => {
this.$emit('refresh');
this.$emit('close');
})
.catch(error => {
alert('提交失败: ' + error.response.data.message);
});
} else {
CourseService.createCourse(formData)
.then(() => {
this.$emit('refresh');
this.$emit('close');
})
.catch(error => {
alert('提交失败: ' + error.response.data.message);
});
}
}
},
watch: {
course: {
immediate: true,
handler(newCourse) {
if (newCourse) {
this.form.name = newCourse.name;
this.form.description = newCourse.description;
this.form.author = newCourse.author;
this.form.sortOrder = newCourse.sortOrder;
} else {
this.form.name = '';
this.form.description = '';
this.form.author = '';
this.form.sortOrder = '';
this.form.coverImage = null;
this.form.video = null;
this.imageUrl = null;
this.videoUrl = null;
}
}
}
}
};
</script>
<style scoped>
.modal {
/* 添加你的样式 */
}
.modal-content {
/* 添加你的样式 */
}
</style>