概要
Nuxt.jsについて調べているとたまにref
という属性を見かけることがあります。
そんなref
属性について自分なりに理解して備忘録としてアウトプットします。
ref属性とは
ref
属性とは、特定のHTML要素を参照するために使用するものです。
使用例
例えば、ページのマウント時にinput
タグにフォーカスを当てたい場合
<!-- Component.vue -->
<template>
<input ref='sample' />
</template>
<script>
export default {
methods: {
inputFocus() {
this.$ref.sample.focus() // "this.$ref.参照名"でref属性を定義した要素を取得できます
}
},
mounted() {
this.inputFocus
}
}
</script>
ref
属性を使用することで、特定の要素を取得して操作することができるようになる。
また、子コンポーネントタグにref
属性を指定することで
親コンポーネントから操作することもできる。
<!-- index.vue -->
<template>
<Component ref='inputComponent' />
</template>
<script>
export default {
mounted() {
this.$ref.inputComponent.inputFocus
// 子コンポーネントであるComponent.vueのinputFocus()メソッドを実行している
}
}
</script>