LoginSignup
5
0

More than 3 years have passed since last update.

[Vue/Nuxt]client-onlyのコンポーネントはrefで取得できない

Last updated at Posted at 2021-03-03

client-onlyはSSRさせるアプリケーションにおいて、SSRさせずにクライアント側で展開させたい場合に使うタグです。

<template>
  <div>
    <client-only>
      no-ssr
    </client-only>
    <p>ssr</p>
  </div>
</template>

このclient-only内に展開したコンポーネントをrefで取得するケースで、まず通常の取得ケースは以下のようになります。

<template>
  <div>
    <client-only>
      <my-component ref="myComponentRef" />
    </client-only>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const myComponentRef = ref(null)
    onMounted(() => {
      console.log(myComponentRef.value)
    })
    return { myComponentRef }
  }
}
</script>

refで空の変数を用意しておいて、テンプレートのrefに代入、onMounted後であればVue v2のthis.$refsの様にスクリプト内でコンポーネントにアクセスできます。
ですが、client-only内に展開したコンポーネントではこの方法ではアクセスできません。
このコードを実行するとmyComponentRef.valuenullとなります。

nextTickを使う

この場合はnextTickを利用すると解決できます。

<script>
import { ref, onMounted, nextTick } from 'vue'

export default {
  setup() {
    const myComponentRef = ref(null)
    onMounted(() => {
      nextTick(() => {
        console.log(myComponentRef.value)
      })
    })
    return { myComponentRef }
  }
}
</script>

おわり

5
0
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
5
0