- 其實
ref
接收的數據可以是:基本類型、對象類型。 - 若
ref
接收的是對象類型,內部其實也是調用了reactive
函數。
<template><div class="person"><h2>汽車信息:一臺{{ car.brand }}汽車,價值{{ car.price }}萬</h2><h2>游戲列表:</h2><ul><li v-for="g in games" :key="g.id">{{ g.name }}</li></ul><h2>測試:{{obj.a.b.c.d}}</h2><button @click="changeCarPrice">修改汽車價格</button><button @click="changeFirstGame">修改第一游戲</button><button @click="test">測試</button></div>
</template><script lang="ts" setup name="Person">
import { ref } from 'vue'// 數據
let car = ref({ brand: '奔馳', price: 100 })
let games = ref([{ id: 'ahsgdyfa01', name: '英雄聯盟' },{ id: 'ahsgdyfa02', name: '王者榮耀' },{ id: 'ahsgdyfa03', name: '原神' }
])
let obj = ref({a:{b:{c:{d:666}}}
})console.log(car)function changeCarPrice() {car.value.price += 10
}
function changeFirstGame() {games.value[0].name = '流星蝴蝶劍'
}
function test(){obj.value.a.b.c.d = 999
}
</script>
3.6. 【ref 對比 reactive】
宏觀角度看:
ref
用來定義:基本類型數據、對象類型數據;
reactive
用來定義:對象類型數據。
- 區別:
ref
創建的變量必須使用.value
(可以使用volar
插件自動添加.value
)。
reactive
重新分配一個新對象,會失去響應式(可以使用Object.assign
去整體替換)。
- 使用原則:
- 若需要一個基本類型的響應式數據,必須使用
ref
。- 若需要一個響應式對象,層級不深,
ref
、reactive
都可以。- 若需要一個響應式對象,且層級較深,推薦使用
reactive
。
3.7. 【toRefs 與 toRef】
- 作用:將一個響應式對象中的每一個屬性,轉換為
ref
對象。 - 備注:
toRefs
與toRef
功能一致,但toRefs
可以批量轉換。 - 語法如下:
<template><div class="person"><h2>姓名:{{person.name}}</h2><h2>年齡:{{person.age}}</h2><h2>性別:{{person.gender}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">修改年齡</button><button @click="changeGender">修改性別</button></div>
</template><script lang="ts" setup name="Person">import {ref,reactive,toRefs,toRef} from 'vue'// 數據let person = reactive({name:'張三', age:18, gender:'男'})// 通過toRefs將person對象中的n個屬性批量取出,且依然保持響應式的能力let {name,gender} = toRefs(person)// 通過toRef將person對象中的gender屬性取出,且依然保持響應式的能力let age = toRef(person,'age')// 方法function changeName(){name.value += '~'}function changeAge(){age.value += 1}function changeGender(){gender.value = '女'}
</script>