Merge branch 'main' into login

This commit is contained in:
yoon 2025-01-21 14:58:38 +09:00
commit 324c0a44a1
10 changed files with 495 additions and 236 deletions

49
src/common/common.js Normal file
View File

@ -0,0 +1,49 @@
/*
작성자 : 공현지
작성일 : 2025-01-17
수정자 :
수정일 :
설명 : 공통 스크립트
*/
import Quill from 'quill';
/*
*템플릿 사용법 : $common.변수
*setup() 사용법 :
const { appContext } = getCurrentInstance();
const $common = appContext.config.globalProperties.$common;
$common.변수
*/
const common = {
// JSON 문자열로 Delta 타입을 변환
contentToHtml(content) {
try {
if (content.startsWith('{') || content.startsWith('[')) {
// Delta 형식으로 변환
const delta = JSON.parse(content);
const quill = new Quill(document.createElement('div'));
quill.setContents(delta);
return quill.root.innerHTML; // HTML 반환
}
return content; // 이미 HTML일 경우 그대로 반환
} catch (error) {
console.error('콘텐츠 변환 오류:', error);
return content; // 오류 발생 시 원본 반환
}
},
// Delta 타입을 JSON 문자열로 변환
deltaAsJson(content) {
if (content && content.ops) {
return JSON.stringify(content.ops); // Delta 객체에서 ops 속성만 JSON 문자열로 변환
}
console.error('잘못된 Delta 객체:', content);
return null; // Delta 객체가 아니거나 ops가 없을 경우 null 반환
}
}
export default {
install(app) {
app.config.globalProperties.$common = common;
}
};

View File

@ -46,20 +46,27 @@
</div>
<!-- 에디터가 표시될 div -->
<div ref="editor"></div>
<!-- Alert 메시지 표시 -->
<div class="invalid-feedback" :class="isAlert ? 'd-block' : ''">내용을 확인해주세요.</div>
</div>
</template>
<script setup>
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import { onMounted, ref, watch, defineEmits } from 'vue';
import { onMounted, ref, watch, defineEmits, defineProps } from 'vue';
import $api from '@api';
const props = defineProps({
isAlert: {
type: Boolean,
default: false,
},
});
const editor = ref(null);
const font = ref('nanum-gothic');
const fontSize = ref('16px');
const emit = defineEmits(['update:data']);
onMounted(() => {
const Font = Quill.import('formats/font');
Font.whitelist = ['nanum-gothic', 'd2coding', 'consolas', 'serif', 'monospace'];
@ -83,21 +90,23 @@ onMounted(() => {
quillInstance.format('size', fontSize.value);
quillInstance.on('text-change', () => {
emit('update:data', quillInstance.root.innerHTML);
const delta = quillInstance.getContents(); // Get Delta format
emit('update:data', delta);
});
watch([font, fontSize], () => {
quillInstance.format('font', font.value);
quillInstance.format('size', fontSize.value);
});
//
let imageUrls = new Set();
// Handle image upload
let imageUrls = new Set();
quillInstance.getModule('toolbar').addHandler('image', () => {
selectLocalImage();
});
quillInstance.on('text-change', (delta, oldDelta, source) => {
emit('update:data', quillInstance.root.innerHTML);
// Emit Delta when content changes
emit('update:data', quillInstance.getContents());
delta.ops.forEach(op => {
if (op.insert && typeof op.insert === 'object' && op.insert.image) {
const imageUrl = op.insert.image;
@ -107,13 +116,11 @@ onMounted(() => {
}
});
});
async function selectLocalImage() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = () => {
const file = input.files[0];
if (file) {
@ -129,22 +136,21 @@ onMounted(() => {
imageUrls.add(fullImageUrl);
}).catch(e => {
toastStore.onToast('잠시후 다시 시도해주세요.', 'e');
toastStore.onToast('잠시후 다시 시도해주세요.', 'e');
});
}
};
}
async function uploadImageToServer(formData) {
try {
const response = await $api.post('img/upload', formData, { isFormData: true });
const imageUrl = response.data.data;
return imageUrl;
const response = await $api.post('quilleditor/upload', formData, { isFormData: true });
const imageUrl = response.data.data;
return imageUrl;
} catch (error) {
toastStore.onToast('잠시후 다시 시도해주세요.', 'e');
throw error;
}
}
function checkForDeletedImages() {
const editorImages = document.querySelectorAll('#editor img');
const currentImages = new Set(Array.from(editorImages).map(img => img.src));
@ -156,14 +162,11 @@ onMounted(() => {
});
}
});
</script>
<style>
@import 'quill/dist/quill.snow.css';
.ql-editor {
min-height: 300px;
font-family: 'Nanum Gothic', sans-serif;
}
</style>
</style>

View File

@ -1,8 +1,8 @@
<template>
<div class="mb-2 row">
<label :for="name" class="col-md-2 col-form-label">
<label :for="name" class="col-md-2 col-form-label" :class="isLabel ? 'd-block' : 'd-none'">
{{ title }}
<span :class="isEssential ? 'text-red' : 'none'">*</span>
<span class="text-danger">*</span>
</label>
<div class="col-md-10">
<input
@ -55,6 +55,11 @@ const props = defineProps({
type: Boolean,
default: false,
},
isLabel : {
type: Boolean,
default: true,
required: false,
},
});
// Emits

View File

@ -11,21 +11,29 @@
/>
</div>
<!-- 게시물 내용 섹션 -->
<div class="col-md-10">
<div :class="contentColClass">
<div class="card-body">
<!-- 태그 -->
<h6 class="badge rounded-pill bg-primary text-white mb-2">
{{ category }}
</h6>
<!-- 제목 -->
<h5 class="card-title">{{ title }}</h5>
<h5 class="card-title">
{{ title }}
<span class="text-muted me-3" v-if="attachment">
<i class="fa-solid fa-paperclip"></i>
</span>
</h5>
<!-- 본문 -->
<p class="card-text str_wrap">{{ content }}</p>
<!-- 날짜 -->
<div class="d-flex justify-content-between">
<small class="text-muted">{{ formatDate(date) }}</small>
<!-- 좋아요와 댓글 -->
<small class="text-muted">{{ formattedDate }}</small>
<!-- 조회수, 좋아요, 댓글 -->
<div>
<span class="text-muted me-3">
<i class="fa-regular fa-eye"></i> {{ views || 0 }}
</span>
<span class="text-muted me-3">
<i class="bx bx-like"></i> {{ likes || 0 }}
</span>
@ -40,49 +48,64 @@
</div>
</template>
<script>
export default {
props: {
img: {
type: String,
default: null,
},
category: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
date: {
type: String,
required: true,
},
likes: {
type: Number,
default: 0,
},
comments: {
type: Number,
default: 0,
},
<script setup>
import { computed } from 'vue';
import { defineProps } from 'vue';
// Props
const props = defineProps({
img: {
type: String,
default: null,
},
methods: {
formatDate(dateString) {
const date = new Date(dateString);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
date.getDate()
).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(
date.getMinutes()
).padStart(2, "0")}`;
},
category: {
type: String,
required: false,
},
};
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
date: {
type: String,
required: true,
},
views: {
type: Number,
default: 0,
},
likes: {
type: Number,
default: 0,
},
comments: {
type: Number,
default: 0,
},
attachment: {
type: Boolean,
default: false,
}
});
// computed
const contentColClass = computed(() => {
return props.img ? 'col-md-10 col-12' : 'col-md-12';
});
// formattedDate computed
const formattedDate = computed(() => {
const date = new Date(props.date);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
date.getDate()
).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(
date.getMinutes()
).padStart(2, "0")}`;
});
</script>
<style>

View File

@ -10,8 +10,10 @@
:title="post.title"
:content="post.content"
:date="post.date"
:views="post.views"
:likes="post.likes"
:comments="post.comments"
:attachment="post.attachment"
/>
</div>
</div>

View File

@ -1,35 +1,126 @@
<template>
<nav aria-label="Page navigation">
<ul class="pagination pagination-rounded justify-content-center">
<!-- <li class="page-item first">
<a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevrons-left bx-sm"></i></a>
</li> -->
<!-- <li class="page-item prev">
<a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevron-left bx-sm"></i></a>
</li> -->
<li class="page-item active">
<a class="page-link" href="javascript:void(0);">1</a>
<!-- 페이지 이동 -->
<li
class="page-item first"
@click="emitPageChange(1)"
:class="{ disabled: isFirstPage }"
>
<a class="page-link" href="javascript:void(0);">
<i class="tf-icon bx bx-chevrons-left bx-sm"></i>
</a>
</li>
<li class="page-item">
<a class="page-link" href="javascript:void(0);">2</a>
<!-- 이전 페이지 이동 -->
<li
class="page-item prev"
@click="emitPageChange(navigateFirstPage-1)"
:class="{ disabled: !hasPreviousPage }"
>
<a class="page-link" href="javascript:void(0);">
<i class="tf-icon bx bx-chevron-left bx-sm"></i>
</a>
</li>
<li class="page-item">
<a class="page-link" href="javascript:void(0);">3</a>
<!-- 페이지 번호들 -->
<li
v-for="page in navigatepageNums"
:key="page"
:class="['page-item', { active: page === currentPage }]"
@click="emitPageChange(page)"
>
<a class="page-link" href="javascript:void(0);">{{ page }}</a>
</li>
<li class="page-item">
<a class="page-link" href="javascript:void(0);">4</a>
<!-- 다음 페이지 이동 -->
<li
class="page-item next"
@click="emitPageChange(navigateLastPage+1)"
:class="{ disabled: !hasNextPage }"
>
<a class="page-link" href="javascript:void(0);">
<i class="tf-icon bx bx-chevron-right bx-sm"></i>
</a>
</li>
<li class="page-item">
<a class="page-link" href="javascript:void(0);">5</a>
</li>
<li class="page-item next">
<a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevron-right bx-sm"></i></a>
</li>
<li class="page-item last">
<a class="page-link" href="javascript:void(0);"><i class="tf-icon bx bx-chevrons-right bx-sm"></i></a>
<!-- 마지막 페이지 이동 -->
<li
class="page-item last"
@click="emitPageChange(pages)"
:class="{ disabled: isLastPage }"
>
<a class="page-link" href="javascript:void(0);">
<i class="tf-icon bx bx-chevrons-right bx-sm"></i>
</a>
</li>
</ul>
</nav>
</template>
</template>
<script setup></script>
<script setup>
import { defineProps, defineEmits } from 'vue';
// Props
const props = defineProps({
currentPage: {
type: Number,
required: true
},
pages: {
type: Number,
required: true
},
prePage: {
type: Number,
required: true
},
nextPage: {
type: Number,
required: true
},
isFirstPage: {
type: Boolean,
required: true
},
isLastPage: {
type: Boolean,
required: true
},
hasPreviousPage: {
type: Boolean,
required: true
},
hasNextPage: {
type: Boolean,
required: true
},
navigatePages: {
type: Number,
required: true
},
navigatepageNums: {
type: Array,
required: true
},
navigateFirstPage: {
type: Number,
required: true
},
navigateLastPage: {
type: Number,
required: true
}
});
//
const emit = defineEmits(['update:currentPage']);
//
const emitPageChange = (page) => {
if (page !== props.currentPage && page >= 1 && page <= props.pages) {
emit('update:currentPage', page);
}
};
</script>

View File

@ -5,13 +5,15 @@ import App from './App.vue'
import router from '@/router'
import dayjs from '@p/dayjs'
import ToastModal from '@c/modal/ToastModal.vue';
import common from '@/common/common.js'
const pinia = createPinia()
pinia.use(piniaPersist)
const app = createApp(App)
app.use(router)
.use(pinia)
.use(common)
.use(dayjs)
.component('ToastModal',ToastModal)
.mount('#app')

View File

@ -1,24 +1,58 @@
<template>
<div class="container-xxl flex-grow-1 container-p-y">
<!-- 검색 -->
<search-bar @update:data="search" />
<!-- 상단 : 검색창, 정렬 셀렉트 박스, 글쓰기 버튼 -->
<div class="row mb-4">
<!-- 검색창 -->
<div class="col">
<search-bar @update:data="search" />
</div>
</div>
<!-- 리스트 -->
<div class="row g-3">
<div class="mt-8">
<div class="row">
<!-- 정렬 셀렉트 박스 -->
<div class="col-md-3 mb-4">
<select class="form-select" v-model="selectedOrder" @change="handleSortChange">
<option value="date">최신날짜</option>
<option value="views">조회수</option>
</select>
</div>
<!-- 글쓰기 버튼 -->
<div class="col-auto ms-auto mb-4">
<router-link to="/board/write">
<WriteButton />
</router-link>
</div>
</div>
<board-card :posts="paginatedList" @click="goDetail" />
<!-- 공지사항 게시물 리스트 -->
<div class="row g-3 mt-2 mt-md-8">
<h3>공지사항</h3>
<board-card :posts="noticeList" @click="goDetail" />
</div>
<!-- 일반 게시물 리스트 -->
<div class="row g-3 mt-8">
<h3>일반게시판</h3>
<board-card :posts="generalList" @click="goDetail" />
</div>
<!-- 페이지네이션 -->
<!-- 페이지네이션 -->
<div class="row g-3">
<div class="mt-8">
<pagination
:current-page="currentPage"
:total-pages="totalPages"
@update:page="changePage"
<Pagination
:currentPage="pagination.currentPage"
:pages="pagination.pages"
:prePage="pagination.prePage"
:nextPage="pagination.nextPage"
:isFirstPage="pagination.isFirstPage"
:isLastPage="pagination.isLastPage"
:hasPreviousPage="pagination.hasPreviousPage"
:hasNextPage="pagination.hasNextPage"
:navigatePages="pagination.navigatePages"
:navigatepageNums="pagination.navigatepageNums"
:navigateFirstPage="pagination.navigateFirstPage"
:navigateLastPage="pagination.navigateLastPage"
@update:currentPage="handlePageChange"
/>
</div>
</div>
@ -35,75 +69,120 @@ import WriteButton from '@c/button/WriteBtn.vue';
import axios from '@api';
//
const list = ref([]);
const generalList = ref([]);
const noticeList = ref([]);
const searchText = ref('');
const selectedOrder = ref('date');
const sortDirection = ref('desc');
const pagination = ref({
currentPage: 1,
pages: 1,
prePage: 0,
nextPage: 1,
isFirstPage: true,
isLastPage: false,
hasPreviousPage: false,
hasNextPage: false,
navigatePages: 10,
navigatepageNums: [1],
navigateFirstPage: 1,
navigateLastPage: 1
});
//
const goDetail = (id) => {
console.log('Navigating to ID:', id)
router.push({ name: 'BoardDetail', params: { id } });
};
//
const search = (e) => {
searchText.value = e.trim();
fetchGeneralPosts(1);
fetchNoticePosts(searchText.value);
};
//
const filteredList = computed(() =>
list.value.filter((item) =>
item.title.toLowerCase().includes(searchText.value.toLowerCase())
)
);
//
const currentPage = ref(1); //
const itemsPerPage = 5; //
//
const paginatedList = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage;
const end = start + itemsPerPage;
return filteredList.value.slice(start, end);
});
//
const totalPages = computed(() => {
return Math.ceil(filteredList.value.length / itemsPerPage);
});
//
const changePage = (page) => {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page;
}
//
const handleSortChange = (event) => {
fetchGeneralPosts(1);
};
//
const fetchPosts = async () => {
const response = await axios.get("board/general");
console.log(response.data.data.list)
// ()
const fetchGeneralPosts = async (page = 1) => {
const response = await axios.get("board/general", {
params: {
page: page,
orderBy: selectedOrder.value,
sortDirection: sortDirection.value,
searchKeyword: searchText.value
}
});
if (response.data && response.data.data && Array.isArray(response.data.data.list)) {
list.value = response.data.data.list.map((post, index) => ({
if (response.data && response.data.data) {
const data = response.data.data;
//
generalList.value = data.list.map((post, index) => ({
...post,
id: post.id || index,
img: post.img || null,
likes: post.likes || 0,
comments: post.comments || 0,
views: post.cnt || 0,
likes: post.likeCount || 0,
comments: post.commentCount || 0,
attachment: post.hasAttachment || false,
}));
//
pagination.value = {
currentPage: data.pageNum,
pages: data.pages,
prePage: data.prePage,
nextPage: data.nextPage,
isFirstPage: data.isFirstPage,
isLastPage: data.isLastPage,
hasPreviousPage: data.hasPreviousPage,
hasNextPage: data.hasNextPage,
navigatePages: data.navigatePages,
navigatepageNums: data.navigatepageNums,
navigateFirstPage: data.navigateFirstPage,
navigateLastPage: data.navigateLastPage
};
} else {
console.error("데이터 오류:", response.data);
}
};
// ()
const fetchNoticePosts = async () => {
const response = await axios.get("board/notices", {
params: {
searchKeyword: searchText.value
}
});
if (response.data && response.data.data && Array.isArray(response.data.data)) {
noticeList.value = response.data.data.map((post, index) => ({
...post,
id: post.id || index,
img: post.img || null,
views: post.cnt || 0,
likes: post.likeCount || 0,
comments: post.commentCount || 0,
attachment: post.hasAttachment || false,
}));
} else {
console.error("Unexpected API response structure:", response.data);
console.error("데이터 오류:", response.data);
}
};
//
const handlePageChange = (page) => {
if (page !== pagination.value.currentPage) {
fetchGeneralPosts(page);
}
};
//
onMounted(() => {
fetchPosts();
fetchGeneralPosts();
fetchNoticePosts();
});
</script>
<style>
/* 필요에 따라 스타일 추가 */
</style>

View File

@ -5,17 +5,17 @@
<div class="card">
<!-- 프로필 헤더 -->
<div class="card-header">
<BoardProfile :boardId="currentBoardId.value" :profileName="profileName" />
<BoardProfile :boardId="currentBoardId" :profileName="profileName" />
</div>
<!-- 게시글 내용 -->
<div class="card-body">
<h5 class="mb-4">{{ boardTitle }}</h5>
<!-- HTML 콘텐츠 렌더링 -->
<div class="board-content" v-html="boardContent"></div>
<div class="board-content text-body" style="line-height: 1.6;" v-html="convertedContent"></div>
<!-- 첨부파일 목록 -->
<ul v-if="attachments.length" class="attachments mt-4">
<li v-for="(attachment, index) in attachments" :key="index">
<a :href="attachment.url" target="_blank">{{ attachment.name }}</a>
<ul v-if="attachments.length" class="attachments mt-4 list-unstyled">
<li v-for="(attachment, index) in attachments" :key="index" class="mb-2">
<a :href="attachment.url" target="_blank" class="text-decoration-none">{{ attachment.name }}</a>
</li>
</ul>
<!-- 댓글 영역 -->
@ -23,10 +23,7 @@
</div>
<!-- 수정 버튼 -->
<div class="card-footer d-flex justify-content-end">
<button
class="btn btn-primary"
@click="goToEditPage"
>
<button class="btn btn-primary" @click="goToEditPage">
수정
</button>
</div>
@ -42,11 +39,14 @@ import BoardProfile from '@c/board/BoardProfile.vue';
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@api';
import Quill from 'quill';
import DOMPurify from 'dompurify';
//
const profileName = ref('익명 사용자');
const boardTitle = ref('제목 없음');
const boardContent = ref('내용 없음');
const boardContent = ref('');
const convertedContent = ref('내용 없음');
const comments = ref([]);
const attachments = ref([]);
@ -54,7 +54,6 @@ const attachments = ref([]);
const route = useRoute();
const router = useRouter();
const currentBoardId = ref(Number(route.params.id));
console.log(currentBoardId.value)
//
const goToEditPage = () => {
@ -71,7 +70,22 @@ const fetchBoardDetails = async () => {
const boardDetail = data.boardDetail || {};
profileName.value = boardDetail.author || '익명 사용자';
boardTitle.value = boardDetail.title || '제목 없음';
boardContent.value = boardDetail.content || '내용 없음';
boardContent.value = boardDetail.content || '';
// Quill Delta HTML
if (boardContent.value) {
try {
const quillContainer = document.createElement('div');
const quillInstance = new Quill(quillContainer);
quillInstance.setContents(JSON.parse(boardContent.value));
convertedContent.value = DOMPurify.sanitize(quillContainer.innerHTML);
} catch (parseError) {
console.error('Delta 데이터 변환 오류:', parseError);
convertedContent.value = '내용을 표시할 수 없습니다.';
}
} else {
convertedContent.value = '내용 없음';
}
attachments.value = data.attachments || [];
comments.value = data.comments || [];
@ -83,7 +97,6 @@ const fetchBoardDetails = async () => {
//
onMounted(() => {
console.log('Route Params:', route.params);
fetchBoardDetails();
});
</script>

View File

@ -9,36 +9,69 @@
<div class="col-xl-12">
<div class="card-body">
<FormInput title="제목" name="title" :is-essential="true" :is-alert="titleAlert" @update:data="title = $event" />
<FormSelect title="카테고리" name="cate" :is-essential="true" :data="categoryList" @update:data="category = $event" />
<FormInput
v-show="category == 1"
title="비밀번호"
name="pw"
type="password"
title="제목"
name="title"
:is-essential="true"
:is-alert="passwordAlert"
@update:data="password = $event"
:is-alert="titleAlert"
v-model="title"
/>
<FormFile title="첨부파일" name="files" :is-alert="attachFilesAlert" @update:data="attachFiles = $event" />
<!-- 카테고리 선택 -->
<div class="mb-4 d-flex align-items-center">
<label class="col-md-2 col-form-label">카테고리 <span class="text-danger">*</span></label>
<div class="d-flex flex-wrap align-items-center mt-3 ms-1">
<div
v-for="(categoryName, index) in categoryList"
:key="index"
class="form-check me-3"
>
<input
class="form-check-input"
type="radio"
:id="`category-${index}`"
:value="index"
v-model="category"
/>
<label class="form-check-label" :for="`category-${index}`">
{{ categoryName }}
</label>
</div>
</div>
</div>
<!-- 비밀번호 필드 -->
<div v-if="category === 1" class="mb-4">
<FormInput
title="비밀번호"
name="pw"
type="password"
:is-essential="true"
:is-alert="passwordAlert"
v-model="password"
/>
</div>
<FormFile
title="첨부파일"
name="files"
:is-alert="attachFilesAlert"
@update:data="attachFiles = $event"
/>
<div class="mb-4">
<label for="html5-tel-input" class="col-md-2 col-form-label">
내용
<span class="text-red">*</span>
<span class="text-danger">*</span>
<div class="invalid-feedback" :class="contentAlert ? 'display-block' : ''">내용을 확인해주세요.</div>
</label>
<div class="col-md-12">
<!-- <TEditor @update:data="content = $event"/> -->
<QEditor @update:data="content = $event" />
</div>
</div>
<div class="mb-4 d-flex justify-content-end">
<button type="button" class="btn btn-info right" @click="goList"><i class='bx bx-left-arrow-alt'></i></button>
<button type="button" class="btn btn-info" @click="goList"><i class='bx bx-left-arrow-alt'></i></button>
<button type="button" class="btn btn-primary ms-1" @click="write"><i class='bx bx-check'></i></button>
</div>
</div>
@ -49,114 +82,73 @@
<script setup>
import QEditor from '@c/editor/QEditor.vue';
import TEditor from '@c/editor/TEditor.vue';
import FormInput from '@c/input/FormInput.vue';
import FormSelect from '@c/input/FormSelect.vue';
import FormFile from '@c/input/FormFile.vue';
import { ref, watch } from 'vue';
import { ref } from 'vue';
import router from '@/router';
import axios from '@api';
const categoryList = ['자유', '익명', '공지사항'];
// input !!
const categoryList = ['자유', '익명', '공지사항']; //
const title = ref('');
const password = ref('');
const category = ref(0);
const category = ref(0); // 0
const content = ref('');
const attachFiles = ref(null);
//input
const titleAlert = ref(true);
const titleAlert = ref(false);
const passwordAlert = ref(false);
const contentAlert = ref(false);
const attachFilesAlert = ref(false);
const goList = () => {
// ,
router.push('/board');
};
const write = async () => {
//
if (!title.value) {
titleAlert.value = true;
return;
} else {
titleAlert.value = false;
}
titleAlert.value = !title.value;
passwordAlert.value = category.value === 1 && !password.value;
contentAlert.value = !content.value;
if (category.value === 1 && !password.value) {
passwordAlert.value = true;
if (titleAlert.value || passwordAlert.value || contentAlert.value) {
return;
} else {
passwordAlert.value = false;
}
if (!content.value) {
contentAlert.value = true;
return;
} else {
contentAlert.value = false;
}
try {
//
const boardData = {
LOCBRDTTL: title.value,
LOCBRDCON: content.value,
LOCBRDPWD: category.value === 1 ? password.value : null,
LOCBRDTYP: category.value === 1 ? 'S' : 'F', // !!
// MEMBERSEQ: id()
LOCBRDTYP: category.value === 1 ? 'S' : 'F',
};
// API
const { data: boardResponse } = await axios.post('board', boardData);
const boardId = boardResponse.data.boardId;
const boardId = boardResponse.data.CMNBRDSEQ;
//
if (attachFiles.value && attachFiles.value.length > 0) {
for (const file of attachFiles.value) {
const realName = file.name.substring(0, file.name.lastIndexOf('.'));
const fileInfo = {
path: "/uploads", // ( )
originalName: realName, //
extension: file.name.split('.').pop(), //
registrantId: 1, // ID ( )
};
const formData = new FormData();
formData.append("MEMBERSEQ",registrantId); //
formData.append("CMNFLEPAT", fileInfo.path); //
formData.append("CMNFLENAM", fileInfo.originalName); // ()
formData.append("CMNFLEORG", fileInfo.originalName); // ()
formData.append("CMNFLEEXT", fileInfo.extension); //
formData.append("CMNFLESIZ", file.size); //
formData.append("CMNFLEREG", fileInfo.registrantId); // ID
const fileNameWithoutExt = file.name.replace(/\.[^/.]+$/, '');
const response = await axios.post(`board/${boardId}/attachments`, formData, {
formData.append('CMNBRDSEQ', boardId);
formData.append('CMNFLEORG', fileNameWithoutExt);
formData.append('CMNFLEEXT', file.name.split('.').pop());
formData.append('CMNFLESIZ', file.size);
formData.append('CMNFLEPAT', 'boardfile');
formData.append('file', file);
await axios.post(`board/${boardId}/attachments`, formData, {
headers: {
"Content-Type": "multipart/form-data",
'Content-Type': 'multipart/form-data',
},
});
}
}
alert("게시물이 작성되었습니다.");
alert('게시물이 작성되었습니다.');
goList();
} catch (error) {
console.error(error);
alert("게시물 작성 중 오류가 발생했습니다.");
alert('게시물 작성 중 오류가 발생했습니다.');
}
};
</script>
<style>
.text-red {
color: red;
text-align: center;
}
</style>