LoginSignup
10
3

More than 1 year has passed since last update.

Vue.js(Nuxt.js)で使用するref属性とは何か

Posted at

概要

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>

参考文献

公式ドキュメント

10
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3