Programming/Vue.js

[Vue.js] ref로 width, height 가져오기

stein 2022. 2. 1. 23:10

ref로 width를 가져오는 걸 단순하게 생각하면 다음과 같이 생각할 수 있다.

<div style="width: 400px">
	<div
		refs="elem"
	>
        hihi
    </div>
</div>

<script>
	const elem = ref()
    
	...something vue things
    
	onMounted(){
		console.log('elem width', elem.value.style.width)
	}
    
	...something vue things
</script>

하지만 이렇게 하면 width가 출력되지 않을 것이다. 그래서 elem.value.style만을 출력해보면..

텅텅

이렇게 비어있다는 것을 알 수 있다.

 

style로 설정해준 width는 없기 때문이다. 따라서 clientHeight, clientWidth 를 사용해야한다. 

 

<div style="width: 400px">
	<div
		refs="elem"
	>
        {{elem.clientWidth}}
    </div>
</div>

<script>
	const elem = ref()
    
	...something vue things
</script>