localhost-front/src/common/common.js

84 lines
2.5 KiB
JavaScript

/*
작성자 : 공현지
작성일 : 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 반환
},
/**
* Date 타입 문자열 포멧팅
*
* @param {string} dateStr
* @return
* 1. Date type 인 경우 예시 '25-02-24 12:02'
* 2. Date type 이 아닌 경우 입력값 리턴
*
*/
dateFormatter(dateStr) {
const date = new Date(dateStr);
const dateCheck = date.getTime();
if (isNaN(dateCheck)) {
return dateStr;
} else {
const { year, month, day, hours, minutes } = this.formatDateTime(date);
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
},
formatDateTime(date) {
const zeroFormat = num => (num < 10 ? `0${num}` : num);
return {
year: date.getFullYear(),
month: zeroFormat(date.getMonth() + 1),
day: zeroFormat(date.getDate()),
hours: zeroFormat(date.getHours()),
minutes: zeroFormat(date.getMinutes()),
seconds: zeroFormat(date.getSeconds()),
};
},
};
export default {
install(app) {
app.config.globalProperties.$common = common;
app.provide('common', common);
},
};