본문 바로가기
▶ Front-End/Vue.js

Vue3 기초 예제 - Local Storage

by 오늘도 코딩 2023. 11. 14.
728x90
반응형

Local Storage에 대한 간단한 설명과 이를 사용하는 기초 예제

*이전 Vue3 기초 예제 - Toast 팝업에 이어서 진행(아래 관련 글 참고)

*자세한 설명 생략

 

 

▷ Local Storage 란?

 

    - 로컬에 존재하는 저장소

 

    - 데이터를 브라우저에 반영구 저장

 

    - 브라우저를 재시작해도 데이터가 남음

       * 불필요한 데이터를 직접 삭제해줘야 하는 단점

 

 

▷ 프로젝트 전체 구조

*이전과 동일 한 부분 생략

 

 

▷ 기초 예제 - Local Storage

*사용자가 입력한 메시지를 Local Storage에 저장/삭제하는 예제

*주석 이외 설명 생략

 

-  LocalStorageUtil.js

import * as CmmUtil from '@/module/CmmUtil'

/**
 * Local Storage Init
 * 
 * @param {*} key 
 * @param {*} list (ref)
 */
function initLastMsg(key, list) {
    localStorage.removeItem(key)
    list.value = []
}

/**
 * Local Storage GET Value
 * 
 * @param {*} key 
 * @param {*} list (ref)
 */
function getLastMsg(key, list) {
    if (null != localStorage.getItem(key)) {
        list.value = JSON.parse(localStorage.getItem(key))
    }
}

/**
 * Local Storage SET Value
 * 
 * @param {*} key 
 * @param {*} value (list in value)
 * @param {*} list (ref)
 */
function setLastMsg(key, value, list) {
    // 리스트 저장
    if (!CmmUtil.nullCheck(value)) {
        list.value.push({ "date": CmmUtil.getFormatDate(new Date()), "msg": value })
    }

    // 로컬 스토리지 저장
    localStorage.setItem(key, JSON.stringify(list.value))
}


export {
    getLastMsg,
    setLastMsg,
    initLastMsg,
}

 

- CmmUtil.js

/**
 * Toast 설정
 * 
 * @param {*} toast 
 * @param {*} code
 */
function setToast(toast, code) {

    const S = "success"
    const E = "error"
    const L = 1300

    if ("0000" == code) { toast.add({ detail: 'Message has been send.', severity: S, summary: S, life: L }) }
    if ("0001" == code) { toast.add({ detail: 'Empty Success', severity: S, summary: S, life: L }) }

    if ("9001" == code) { toast.add({ detail: 'Please write your message.', severity: E, summary: E, life: L }) }
    if ("9002" == code) { toast.add({ detail: 'Please write your ID.', severity: E, summary: E, life: L }) }
    if ("9999" == code) { toast.add({ detail: 'Server Error. please try again.', severity: E, summary: E, life: L }) }
}

/**
 * Date Formater
 * 
 * @param {*} date 
 * @returns [YYYY-MM-dd hh:mm:ss]
 */
function getFormatDate(date) {
    const YYYY = String(date.getFullYear())
    const MM = String((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1))
    const dd = String(date.getDate() >= 10 ? date.getDate() : "0" + date.getDate())
    const hours = String(date.getHours() >= 10 ? date.getHours() : "0" + date.getHours())
    const minuts = String(date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes())
    const seconds = String(date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds())
    return "[" + YYYY + "-" + MM + "-" + dd + " " + hours + ":" + minuts + ":" + seconds + "]"
}

/**
 * Null Check
 * 
 * @param {*} str 
 * @returns default false
 */
function nullCheck(str) {
    if ("" == str) { return true }
    if (null == str) { return true }
    if (str.replace(/\s/g, '').length < 1) { return true }

    return false
}


export {
    setToast,
    getFormatDate,
    nullCheck,
}

 

- MsgSendCmp.vue

<template>
    <div style="width: 100%; height: 100%; position: relative; text-align: center;">
        <h3>💌 Message</h3>
        <div>
            <Textarea v-model="inMsg" rows="5" cols="100" spellcheck="false" autoResize />
        </div><br />
        <div>
            <Button label="Send" severity="Primary" raised @click="sendMsg()" />
        </div><br /><br />
        <div style="text-align: left; margin-left: 20%;">
            <h3 style="display: inline; margin-right: 1%;">💬 지난 메시지</h3>
            <Button label="Empty" severity="danger" raised style="width: 100px; height: 20px;" @click="emptyMsg()" />
            <div style="white-space:pre; text-align: left">
                <h5 v-for="(obj, idx) in lastMsgList.slice().reverse()" :key="obj">
                    <p>{{ obj.date }}
                        <button @click="selectMsg(idx)">📌</button>
                        <button @click="deleteMsg(idx)">❌</button>
                    </p>
                    <p>{{ obj.msg }}</p>
                </h5>
            </div>
        </div>
    </div>
    <Toast />
</template> 

<script setup>
/** Vue */
import { ref, onMounted } from 'vue'

/** Util */
import * as CmmUtil from '@/module/CmmUtil'
import * as LocalStorageUtil from '@/module/LocalStorageUtil'

/** PrimeVue */
import Textarea from 'primevue/textarea'
import Button from 'primevue/button'

/** PrimeVue Toast */
import Toast from 'primevue/toast';
import { useToast } from "primevue/usetoast"

/** Axios */
import * as AxiosModule from '@/module/AxiosModule'

onMounted(() => {
    /** Local Storage GET Value */
    LocalStorageUtil.getLastMsg(lastMsgKey, lastMsgList)
    /** 사용자 입력 메세지 초기화 */
    inMsgInit()
})

/** 사용자 입력 메시지 */
const inMsg = ref("")

/** 지난 메시지 */
const lastMsgKey = "lastMsg"
const lastMsgList = ref([])

/** Toast */
const toast = useToast()

/** 사용자 입력 메세지 초기화 */
function inMsgInit() {
    if (0 == lastMsgList.value.length) {
        inMsg.value = ""
    } else {
        inMsg.value = lastMsgList.value[lastMsgList.value.length - 1].msg
    }
}

/** 지난 메시지 선택 복사 */
function selectMsg(idx) {
    inMsg.value = lastMsgList.value[lastMsgList.value.length - (idx + 1)].msg
    window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); // 스크롤 맨위 이동
}

/** 지난 메시지 선택 삭제 */
function deleteMsg(idx) {
    // 리스트에서 삭제
    lastMsgList.value.splice(lastMsgList.value.length - (idx + 1), 1)

    /** Local Storage SET Value */
    LocalStorageUtil.setLastMsg(lastMsgKey, null, lastMsgList)

    /** 사용자 입력 메세지 초기화 */
    inMsgInit()
}

/** 지난 메시지 전체 삭제 */
function emptyMsg() {
    LocalStorageUtil.initLastMsg(lastMsgKey, lastMsgList);
    inMsg.value = ""
    CmmUtil.setToast(toast, "0001")
}

/** Send message */
async function sendMsg() {

    /** Validation */
    if (CmmUtil.nullCheck(inMsg.value)) { return CmmUtil.setToast(toast, "9001") }
    if (CmmUtil.nullCheck(localStorage.getItem("ID"))) { return CmmUtil.setToast(toast, "9002") }

    /* 요청 값 설정 */
    const REQ_DATA = {
        "src": "WAS",
        "dest": localStorage.getItem("ID"),
        "cmd": "Ctrl",
        "params": [inMsg.value]
    }

    /* CMS POST Send message API */
    const resVO = await AxiosModule.sendPost(AxiosModule.API_LIST['CMS-SEND-MSG'], REQ_DATA)
    if (resVO == 200) {

        /** Local Storage SET Value */
        LocalStorageUtil.setLastMsg(lastMsgKey, inMsg.value, lastMsgList)

        CmmUtil.setToast(toast, "0000")
    } else {
        CmmUtil.setToast(toast, "9999")
    }
}
</script>

 

 

▷ 결과 확인

*① ~ ④ : 로컬 스토리지 관련 결과

*이후 기능 관련 결과

 

① 초기 화면

 

② 보낸 메시지 로컬 스토리지 저장

 

③ 크롬 개발자 모드 > 애플리케이션 > 로컬 스토리지 저장 결과

 

④ 전체 삭제 후 로컬 스토리지 삭제 결과

 

 

⑤ 버튼 클릭시 입력 창에 복사

 

⑥ 선택한 메시지 삭제 후 입력창에 가장 최근 메시지로 복사

 

⑦ 줄바꿈 저장과 중간 값 삭제 후 결과

 

*이외 결과 생략

 

 

▷ 참고

 

[JavaScript] 웹 스토리지(localStorage, sessionStorage)란?

웹 스토리지란? 웹 스토리지는 *쿠키와 비슷하게 해당 도메인과 관련된 특정 데이터를 서버가 아니라 클라이언트에 저장 할 수 있도록 하는 기능입니다. HTML5에 도입된 새로운 기능으로, 쿠키와

j-su2.tistory.com

 

 

▷ 관련 글

 

Vue3 기초 예제 프로젝트 정리

Vue3 기초 예제 프로젝트 구조 및 소스 정리 *관련 글이 점점 늘어나 하나로 통합하기 위함 *이 글에서만 싱크 맞춤 *주석 이외 설명 생략 *자세한 설명 생략 ▷ 프로젝트 전체 구조 < 파일 따라가

coding-today.tistory.com

 

Vue3 기초 예제 - Toast 팝업(Primevue)

사용자로부터 입력받는 간단한 페이지와 Primevue ToastService 사용 예제 *새로운 프로젝트로 진행 *API 관련 설명 생략 *자세한 설명 생략 ▷ 프로젝트 전체 구조 ▷ Primevue + ToastService 설치 *vue-cli를

coding-today.tistory.com

 

 

728x90
728x90

댓글