음악, 삶, 개발
클릭한 위치에 요소 생성하기 본문
<!-- App.vue -->
<template>
<div
id="box"
@mousedown="mouseDown"
>
<div
class ="box-child"
v-for ="(each, index) in boxChilds"
:key ="index"
:style="each"
@mousedown.stop="doNothing /* 이거 없으면 부모 div 의 event 함수 실행됨. */"
></div>
</div>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const boxChilds = reactive([])
function getRandomColor() {
const r = Math.floor(Math.random() * 100) + 100
const g = Math.floor(Math.random() * 100) + 100
const b = Math.floor(Math.random() * 100) + 100
return `rgb(${r}, ${g}, ${b})`
}
function mouseDown(e) {
const childSize = 20;
const childStyle = {
width : childSize + 'px',
height : computed(() => childStyle.width),
left : e.offsetX - (childSize / 2) + 'px',
top : e.offsetY - (childSize / 2) + 'px',
backgroundColor : getRandomColor()
}
boxChilds.push(childStyle)
}
function doNothing(e) {
console.log(e)
}
return { boxChilds, mouseDown, doNothing }
}
}
</script>
<style>
#box {
position : absolute;
left : 20px;
top : 20px;
width : 80%;
height : 80%;
background-color : darkgreen;
overflow: hidden;
}
.box-child {
box-sizing : border-box;
position : absolute;
background-color : red;
}
.box-child:hover {
border: 2px solid white;
}
</style>