뷰(Vue)

Vue3에서 Toast Alert창 적용하기.

뭘하지 2024. 1. 8. 15:36
반응형

 

Toast alert 란 말그대로 토스트기에 빵을 넣으면 따악~ 튀어나오는 형태의 알림창을 말한다.

실제로 제공하는 깃허브에 들어가면 보이는 모습은 다음과 같다.

기존 프로젝트에서 PrimeVue에서 제공하는 Toast alert창을 사용하고자 했으나...뭔가 정상동작하지 않았다.
별도의 플러그인을 설치하여 Vue3에서 js에 사용하고자 하는 형태로 가공하여 사용하려고 한다.

 

 

Vue3를 지원하는 Toast (MIT 라이센스) (2년전이 최종 git수정)

Vue-Toastification

 

Vue-Toastification

 

vue-toastification.maronato.dev

깃 주소

https://github.com/Maronato/vue-toastification

 

GitHub - Maronato/vue-toastification: Vue notifications made easy!

Vue notifications made easy! Contribute to Maronato/vue-toastification development by creating an account on GitHub.

github.com

 

설치

npm install vue-toastification@next

플러그인 등록

main.js

// Toast plugin
import Toast from 'vue-toastification';
import 'vue-toastification/dist/index.css';

const options = {};
app.use(Toast, options);

toast를 사용할 기본 js를 생성함

import { useToast } from 'vue-toastification';
const defaultOptions = {
    msg: 'My toast content',
    timeout: 3000,
    type: 'default', // or "success", "error", "default", "info" and "warning"
    closeButton: 'button', // button 버튼나타남, false 버튼없음
    showCloseButtonOnHover: true, // true, false
    hideProgressBar: false, // true, false
    pauseOnHover: false, // true, false
    position: 'top-center', // top-right, top-center, top-left, bottom-right, bottom-center, bottom-left.
    icon: true, //기본아이콘 true, 아이콘 컴포넌트가 있다면 해당 컴포넌트를 연결해도 됨.
};
const toast = useToast();

export default {
    toast: {
        setToast: (options) => {
            const mergedOptions = { ...defaultOptions, ...options };
            toast(mergedOptions.msg, mergedOptions);
        },
        successToast: (msg) => {
            const options = {
                type: 'success',
            };
            const mergedOptions = { ...defaultOptions, ...options };
            toast(msg, mergedOptions);
        },
        errorToast: (msg) => {
            const options = {
                type: 'error',
            };
            const mergedOptions = { ...defaultOptions, ...options };
            toast(msg, mergedOptions);
        },
        defaultToast: (msg) => {
            const options = {
                type: 'default',
            };
            const mergedOptions = { ...defaultOptions, ...options };
            toast(msg, mergedOptions);
        },
        infoToast: (msg) => {
            const options = {
                type: 'info',
            };
            const mergedOptions = { ...defaultOptions, ...options };
            toast(msg, mergedOptions);
        },
        warningToast: (msg) => {
            const options = {
                type: 'warning',
            };
            const mergedOptions = { ...defaultOptions, ...options };
            toast(msg, mergedOptions);
        },
    },
};

위와같이 설정해두고 해당js를 불러온 뒤 사용 했다.

별도로 커스텀 하고싶다면 setToast를 호출하고 아닌경우 기본 지정된 형태에 default값으로 사용하는 형태로 동작하게 했다.

 

 

반응형