document.querySelector('h1') 대신해 ref 사용해 봅니다.
h1에 ref 속성을 부여하고,
this.$refs.hello.textContent 선택 할 수 있습니다.
단, mounted() 라이프사이클 훅에서 가능합니다.
컴포넌트
<template>
<h1 ref="hello">
Hello world
</h1>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.hello.textContent)
}
}
</script>
자식 컴포넌트의 최상위 요소가 2개 이상 일 때, 그 중 선택하여 ref="good" 부여하고, 부모 컴포넌트에서 this.refs.good 찾아 선택 할 수 있습니다.
부모 컴포넌트
<template>
<Hello ref="hello" />
</template>
<script>
import Hello from '~/components/HelloWorld'
export default {
components: {
Hello
},
mounted() {
console.log(this.$refs.hello.$refs.good)
}
}
</script>
자식 컴포넌트
<template>
<h1>Hello~</h1>
<h1 ref="good">
Hel2
</h1>
</template>