vue에서는 document.querySelector를 그다지 쓰지 않는다. 대신 ref로 요소를 참조함!!
- template 내의 셀렉터에 ref 속성을 주면, mounted에서
this.$refs.이름
으로해당 셀렉터를 가져올 수 있다
<template> <h1 ref="hi"> hi </h1> </template> <script> export default { mounted() { console.log(this.$refs.hi) }, } </script>
- 상위 컴포넌트에서 하위 컴포넌트의 template 셀렉터들을 접근 할 수 있다
- 셀렉터가 한개일 때 :
this.$refs.이름.$el
- 두개 이상일 때 :
this.$refs.이름.$refs.셀렉터이름
//App.vue <template> <Hello ref="hello" /> </template> <script> import Hello from '~/Hello/Hello' export default { components: { Hello }, mounted() { console.log(this.$refs.hello.$el) } } </script>
//App.vue <template> <Hello ref="hello" /> </template> <script> mounted() { console.log(this.$refs.hello.$refs.hi) console.log(this.$refs.hello.$refs.hehe) } } </script> //Hello.vue <template> <h1 ref="hi">hi</h1> <h2 ref="hehe">hehe</h2> </template>
$nextTick
: 화면이 리렌더링된 후에 실행하는 메서드
<template> <button v-if="!isEdit" @click="onEdit" > editmode </button> <input v-else ref="editor" @keyup.enter="isEdit = false" > </template> <script> export default { methods: { onEdit() { this.isEdit = true this.$nextTick(()=> { this.$refs.editor.focus() // isEdit가 true가 되고 input이 나타나면 실행 }) } } } </script>