내가 한 노력들

[ vue ] vue-loading-overlay 설치 및 적용하는 법 본문

IT 공부/Vue

[ vue ] vue-loading-overlay 설치 및 적용하는 법

JONGI-N CHOI 2022. 12. 8. 13:00

loading overlay란, 비동기 작업이나 실행완료까지 시간이 걸리는 작업을 하는 경우에 로딩중이라는 것을 표현해주는 것을 의미합니다. 

위의 이미지와 같이 loading overlayd에는 동그란 이미지, 막대 이미지, 프로그레스 바 등등 다양한 종류가 있습니다. 

또한 loading overlay의 중요한 역할중 하나는 어떠한 작업이 진행중에 유저가 다른 작업을 하는 것을 방지합니다. 

 

예를 들어, 사진을 업데이트 하고 사진을 수정하는 웹사이트가 있는 경우에 사진 업데이트가 완료된 후에 수정할 수 있는건데 업데이트가 완료되기도 전에 수정을 하는 것은 문제가 발생할 수 있습니다.

 

그러한 경우를 막기위해서 업데이트 중에는 loading overlay를 통해서 다른 요소의 클릭등의 작업을 방지할 수 있습니다. 


설치 

npm 이용

npm i vue-loading-overlay

 

plugin 방식으로의 사용

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store

// loading overlay 
import { LoadingPlugin } from 'vue-loading-overlay';

createApp(App).use(store).use(router).use(LoadingPlugin).mount('#app')

보통 vue를 사용할 때, router나 vuex를 사용하게되면 main.js에 설정해주듯이 LoadingPlugin도 마찬가지로 설정해주면 모든 컴포넌트에서 LoadingPlugin을 사용할 수 있습니다. 

 

<template>
    <button @click="showLoadingOverlay">show</button>
    <button @click="hideLoadingOverlay">hide</button>
</template>

<script>
    export default {
        data() {
            return {
                loader: '',
            }
        },
        methods: {
            showLoadingOverlay() {
                this.loader = this.$loading.show({
                    // Optional parameters
                    container: null,
                    width: 100,
                    height: 100,
                    loader: "bars",
                    canCancel: false,
                });
                
                setTimeout(() => {
                
                    this.loader.hide();
                }, 3000)
            },
        }
    }
</script>

사용은 매우 간단합니다. 

show 버튼 클릭시에 showLoadingOverlay 메소드를 실행시킵니다. 

 

main.js 에서 vue app에 loadingplugin을 추가했기 때문에, vue 속성에 loading을 사용할 수 있게 되고, vue의 내장속성이기 때문에 "$"를 붙혀서 접근을 합니다. 

 

show()를 사용하면 loading overlay가 화면에 보여지게 되는데, 여기서 여러가지 옵션을 추가할 수 있습니다. 

 

위의 코드에서 사용한 옵션에 대해서 짧게 설명을 하자면, container에 null을 넣게 되면 전체 화면을 대상으로 overlay가 표시됩니다. 

특정 요소에 대해서 overlay를 사용하고 싶은 경우에는, 해당 요소를 넣어 주면 됩니다. (vue의 refs 속성을 이용해서 선택해서 넣어주면 쉽게 넣을 수 있습니다.)

 

width와 height는 loading overlay 아이콘의 크기를 설정할 수 있고, 

loader는 아이콘의 모양을 정할 수 있습니다. bars 는 막대형태 spinner는 원형 형태가 돌아가는 형식 

canCancel은 유저가 overlay를 취소할 수 있을지 없을지를 true와 false로 정하는데 false로 하면 유저가 도중에 취소하는 것이 불가능하고, true로 하게되면 유저가 클릭을하거나 esc를 눌렀을 때 overlay가 취소되게 됩니다. 

 

그밖에도 다양한 옵션이 존재하니 필요한 상황에 맞춰서 잘 사용하면 됩니다. 

옵션 

active Boolean false Show loading by default when true, use it as v-model:active
can-cancel Boolean false Allow user to cancel by pressing ESC or clicking outside
on-cancel Function ()=>{} Do something upon cancel, works in conjunction with can-cancel
is-full-page Boolean true When false; limit loader to its container^
transition String fade Transition name
color String #000 Customize the color of loading icon
height Number * Customize the height of loading icon
width Number * Customize the width of loading icon
loader String spinner Name of icon shape you want use as loader, spinner or dots or bars
background-color String #fff Customize the overlay background color
opacity Number 0.5 Customize the overlay background opacity
z-index Number 9999 Customize the overlay z-index
enforce-focus Boolean true Force focus on loader
lock-scroll Boolean false Freeze the scrolling during full screen loader

 

위의 예제는 단순 버튼을 클릭함으로써 overlay를 실행했습니다만, 보통 overlay를 사용하는 경우는 비동기 통신을 하는 경우, overlay를 보여주고 비동기 통신이 완료되었을 때 다시 overlay를 숨기는 형식으로 많이 사용합니다. 

 

try {

   this.showLoadingOverlay();
   ... 비동기 통신
   
} catch (e) {

    ...error 처리
    
} finally {

    this.loader.hide();
}

위와 같이 비동기 통신시에 overlay를 실행시키고, 비동기 통신의 결과에 상관없이 finally에서 overlay를 종료시키는 방식입니다. 

 


위에는 plugin방식으로만 설명했지만, 컴포넌트로써 사용하는 방법이나 다른 자세한 방식에 대해서는 참고url을 통해서 공부하는 것을 추천합니다!

https://www.npmjs.com/package/vue-loading-overlay

 

vue-loading-overlay

Vue.js component for full screen loading indicator.. Latest version: 6.0.2, last published: a month ago. Start using vue-loading-overlay in your project by running `npm i vue-loading-overlay`. There are 73 other projects in the npm registry using vue-loadi

www.npmjs.com