1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vue】refはrefをアンラップするって理解してる?

Posted at

↓refでいっぱい囲っちゃえ

const num = ref(ref(ref(ref(ref(123)))))

123を出力するには、、

console.log(num.value.value.value.value.value)

かと思いきや上記は誤りでエラーとなる。。

console.log(num.value)

が正解。


じゃあこれは?

const obj = ref({
  num: ref(123)
})

これもアンラップされるので、

console.log(obj.value.num)

が正解。

いつ困るの?

僕の場合こんなこととしててref in refが生まれました。

const useUser = (id: number) => {
  const profile = ref<string>()
  const fetchProfile = () => {
    profile.value = 'Hello'
  }
  return {
    id,
    profile
  }
}

const id = computed(() => Number(route.params.id))
const user = ref(useUser(id.value))
watch(id, () => user.value = useUser(id.value))

refに囲われているものとそうでないものとでは元は同じ型だったとしても構造が異なってしまうので色々問題になります。

shallowRefを使おう

const obj = shallowRef({
  num: ref(123)
})
console.log(obj.value.num.value) // 123

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?