Development/Vue.js
[Vue.js] plugin으로 toast 만들기
레오나르도 다빈츠
2022. 2. 19. 19:06
토스트를 띄우려고 컴포넌트를 만들던 중, 메세지 하나 띄우는데 많은 작업이 필요없다고 판단하여 플러그인으로 만들었다.
실행되면 <body>에 토스트용 <div>가 추가되고 2초뒤에 사라지는 로직이다.
📄 plugins/toast.js
import Vue from 'vue'
const customToast = {
install(Vue) {
Vue.prototype.$_toast = function (msg) {
removeToast()
// 1. id가 'toast'인 div 생성
let toastDiv = document.createElement('div')
toastDiv.setAttribute('id', 'toast')
// 2. <p> 태그안에 매개변수 msg를 append
let textEl = document.createElement('p')
textEl.appendChild(document.createTextNode(msg))
toastDiv.appendChild(textEl)
// 3. 만들어진 div를 최상단인 <body> 안에 append
document.body.appendChild(toastDiv)
// 4. 2초 뒤에 사라지게 만들기
let targetToast = document.getElementById('toast')
setTimeout(function () {
if (targetToast !== null) {
targetToast.remove()
}
}, 2000)
}
},
}
// 기존 토스트가 남아있다면 삭제
function removeToast() {
let toast = document.getElementById('toast')
if (toast !== null) {
toast.remove()
}
}
Vue.use(customToast)
📄 호출방법
showToast() {
let msg = '토스트입니다.'
this.$_toast(msg)
}
📄 CSS
#toast {
z-index: 1000;
height: 52px;
width: calc(100% - 40px);
padding: 0 16px;
background-color: black;
border-radius: 8px;
position: fixed;
bottom: 52px;
left: 50%;
display: flex;
align-items: center;
transform: translate(-50%, -50%);
p {
color: #fff;
font-size: 15px;
letter-spacing: -0.5px;
}
}
개인적으로 공부한 내용을 정리하는 블로그로
잘못된 개념을 게시하지않도록 주의하고 있으나 오류가 있을 수 있습니다.