refとshallowRefが実際どう違うのかわからなかったので確認
// 普通のref
const normal = ref({name: 'Tama'})
const normalName = computed(() => `normalRef.value.name: ${normal.value.name}`)
console.log('①', normalName.value); // ① normalRef.value.name: Tama
// shallowRef
const shallow = shallowRef({name: 'Tama'})
const shallowName = computed(() => `shallowRef.value.name: ${shallow.value.name}`)
console.log('②', shallowName.value); // ② shallowRef.value.name: Tama
// オブジェクト内部の値を変更すると...
normal.value.name = 'Mike'
// reactiveなのでcomputedが再計算される
console.log('③', normalName.value); // ③ normalRef.value.name: Mike
// オブジェクト内部の値を変更しても...
shallow.value.name = 'Mike'
// reactiveではないのでcomputedは再計算されない
console.log('④', shallowName.value); // ④ shallowRef.value.name: Tama
ref()
は引数がオブジェクトだった場合に内部でreactive
を呼び出してる(つまり、最初からreactive()
で作った場合と同じ)。一方shallowRef()
は引数のオブジェクトをリアクティブ変換せずにそのまま保持している。
上の例ではref
, shallowRef
のオブジェクト内のname
プロパティを変更している。
ref
ではリアクティブなのでcmputed
が再計算されるが、shllowRef
ではされない。
shallowRef
にオブジェクトを渡して、かつその中身に依存したcomputed
やwatch
を書く場合には注意。上の例みたいに変更検知ができなくなる。shallowRef
を使った方がよさそうref
によるリアクティブ化は再帰的に実行されるので、オブジェクトの構造が深くて大きいとパフォーマンスに影響するかも。この場合にもshallowRef
テンプレートrefの場合ってどうなってるの?DOM要素が入ってるはずだけどこれも再帰的にreactive化されてる?shallowRef
でもいいの?