매치히어에는 스터디, 프로젝트를 비공개로 모집할 수 있다. 비공개 처리를 하면, 일반 유저의 목록에는 보이지 않기에 초대 링크를 통해 접근할 수 있는데, 초대 링크를 페이지에 그대로 노출하는 것 보다는 "링크 복사하기" 버튼을 만들어 클릭하면 클립보드에 복사될 수 있도록 하면 좋을 것 같아 구현하였다.
Vue 3를 통해 구현하였지만, 방식 자체는 어디에나 적용될 수 있다.
<input type="hidden" />
<template>
<h1>클립보드 구현하기</h1>
<div>
<p class="clipboard">Merry X-mas</p>
<input ref="inputEl" type="hidden" value="그만 행복하세요 ^^7" />
<button @click="handleCopy">클립보드 복사하기</button>
</div>
<input type="text" placeholder="복사한 것을 붙여넣으세요" />
</template>
<script>
import { ref } from "vue"
export default {
setup() {
// 숨겨진 요소를 직접 접근할 수 있도록 변수를 선언
const inputEl = ref(null)
const handleCopyForIE = () => {
// hidden이었던 input의 타입을 text로 변경한다.
inputEl.value.setAttribute("type", "text")
// input을 선택한다.
inputEl.value.select()
// 복사를 수행한다.
document.execCommand("copy")
// text 타입을 hidden으로 변경한다.
inputEl.value.setAttribute("type", "hidden")
alert("execCommand를 통해 내용이 복사되었습니다")
}
const handleCopy = () => {
if (inputEl.value === null) { return }
// clipboard를 지원하지 않는다면,
// execCommand를 통해 복사할 수 있도록 한다.
if (!navigator.clipboard) {
handleCopyForIE()
return
}
navigator.clipboard.writeText(inputEl.value.value)
.then(() => alert("clipboard API를 통해 내용이 복사되었습니다"))
.catch(() => handleCopyForIE())
}
}
}
</script>
document.execCommand를 이용해 복사할 때에는 input이 hidden 상태이면 안된다. select()
를 통해 input 요소를 선택하는데, hidden 상태인 input은 select()
할 수 없기 때문이다.
document.execCommand는 Deprecated 메서드로 사용을 권장하지 않는다.
모두 행복하세요 ^^7