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.value
はnull
となります。
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>
おわり