Vue3 中 ref 的優勢

1. 允許使用任何值類型

2. 一個包含對象類型值的 ref 可以響應式地替換整個對象:

const objectRef = ref({ count: 0 })

// 這是響應式的替換
objectRef.value = { count: 1 }

3. ref 被傳遞給函數或是從一般對象上被解構時,不會丟失響應性:

const obj = {
  foo: ref(1),
  bar: ref(2)
}

// 該函數接收一個 ref
// 需要通過 .value 取值
// 但它會保持響應性
callSomeFunction(obj.foo)

// 仍然是響應式的
const { foo, bar } = obj

4. ref 在響應式對象中的解包(數組和集合類型除外)

const count = ref(0)
const state = reactive({
  count
})

console.log(state.count) // 0

state.count = 1
console.log(count.value) // 1 

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章