75 lines
2.0 KiB
JavaScript
75 lines
2.0 KiB
JavaScript
const { postForm, uploadFile } = require("../../utils/api");
|
|
const { getActiveClassId, showError } = require("../../utils/page-helpers");
|
|
|
|
Page({
|
|
data: {
|
|
title: "",
|
|
content: "",
|
|
images: [],
|
|
loading: false
|
|
},
|
|
|
|
onLoad() {
|
|
wx.setNavigationBarTitle({ title: "发布动态" });
|
|
},
|
|
|
|
onTitleInput(event) {
|
|
this.setData({ title: event.detail.value });
|
|
},
|
|
|
|
onContentInput(event) {
|
|
this.setData({ content: event.detail.value });
|
|
},
|
|
|
|
chooseImages() {
|
|
wx.chooseMedia({
|
|
count: 9 - this.data.images.length,
|
|
mediaType: ["image"],
|
|
sourceType: ["album", "camera"],
|
|
success: (res) => {
|
|
const paths = (res.tempFiles || []).map((item) => item.tempFilePath);
|
|
this.setData({ images: [...this.data.images, ...paths].slice(0, 9) });
|
|
}
|
|
});
|
|
},
|
|
|
|
removeImage(event) {
|
|
const index = Number(event.currentTarget.dataset.index);
|
|
this.setData({
|
|
images: this.data.images.filter((_, itemIndex) => itemIndex !== index)
|
|
});
|
|
},
|
|
|
|
async submit() {
|
|
const title = this.data.title.trim();
|
|
const content = this.data.content.trim();
|
|
if (!title) {
|
|
wx.showToast({ title: "请输入标题", icon: "none" });
|
|
return;
|
|
}
|
|
this.setData({ loading: true });
|
|
try {
|
|
const classId = getActiveClassId();
|
|
const created = await postForm("/api/timeline/", {
|
|
title,
|
|
content,
|
|
class_id: String(classId || "")
|
|
});
|
|
for (let index = 0; index < this.data.images.length; index += 1) {
|
|
await uploadFile(`/api/timeline/${created.id}/images`, this.data.images[index]);
|
|
}
|
|
wx.showToast({ title: "已发布", icon: "success" });
|
|
const pages = getCurrentPages();
|
|
const previousPage = pages[pages.length - 2];
|
|
if (previousPage?.setData) {
|
|
previousPage.setData({ needsRefresh: true });
|
|
}
|
|
setTimeout(() => wx.navigateBack(), 500);
|
|
} catch (error) {
|
|
showError(error, "发布失败");
|
|
} finally {
|
|
this.setData({ loading: false });
|
|
}
|
|
}
|
|
});
|