新聞中心
1、ref
ref 屬性除了能夠獲取元素外,也可以使用 ref 函數(shù),創(chuàng)建一個(gè)響應(yīng)式數(shù)據(jù),當(dāng)數(shù)據(jù)值發(fā)生改變時(shí),視圖自動(dòng)更新。

創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢想脫穎而出為使命,1280元臨縣做網(wǎng)站,已為上家服務(wù),為臨縣各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
{{ str }}
2、isRef
檢查變量是否為一個(gè)被 ref 包裝過的對象,如果是返回 true ,否則返回 false。
import { ref, isRef, reactive } from 'vue'
let str: string = ref('我是張三')
let num: number = 1
let per = reactive({ name: '代碼女神', work: '程序媛' })
console.log('strRes', isRef(str)) //true
console.log('numRes', isRef(num)) //false
console.log('perRes', isRef(per)) //false3、toRef
創(chuàng)建一個(gè) ref 對象,其 value 值指向另一個(gè)對象中的某個(gè)屬性。
toRef(obj, key) 將對象中的某個(gè)值轉(zhuǎn)化為響應(yīng)式數(shù)據(jù),分為兩種情況:
- toRef 定義原始非響應(yīng)式數(shù)據(jù),修改值時(shí),原始數(shù)據(jù)和 copy 數(shù)據(jù)都會(huì)變的,但是視圖不更新。
{{ obj.name }} ------- {{ name }}
注意:如果是在 DOM 掛載之前調(diào)用 chang 方法,改變數(shù)值,此時(shí)數(shù)據(jù)和視圖都會(huì)發(fā)生改變。
- toRef 定義原始數(shù)據(jù)響應(yīng)式數(shù)據(jù),修改值時(shí),原始數(shù)據(jù),和 copy 數(shù)據(jù)都會(huì)改變,視圖也會(huì)更新。
{{ obj.name }} ------- {{ name }}
最終值為 “李四”。
4、toRefs
toRefs 用來解構(gòu) ref、reactive 包裹的響應(yīng)式數(shù)據(jù)。接收一個(gè)對象作為參數(shù),遍歷對象上的所有屬性,將對象上的所有屬性變成響應(yīng)式數(shù)據(jù)。
let obj = reactive({
name: '姓名',
age: 18,
})
let { name, age } = toRefs(obj)
const chang = () => {
name.value = '鉆石王老五'
age.value++
}
{{ name }} ------- {{ age }}
toRefs 解構(gòu)數(shù)據(jù)時(shí),如果某些參數(shù)作為可選參數(shù),可選參數(shù)不存在時(shí)就會(huì)報(bào)錯(cuò),如:
let obj = reactive({
name: '姓名',
age: 18,
})
let { name, age, work } = toRefs(obj)
const chang = () => {
name.value = '鉆石王老五'
age.value++
console.log('work', work.value)
work.value = '程序媛'
}此時(shí)可以使用 toRef 解決此問題,使用 toRef 解構(gòu)對象某個(gè)屬性時(shí),先檢查對象上是否存在該屬性,如果存在就繼承對象上的屬性值,如果不存在就會(huì)創(chuàng)建一個(gè)。
修改上邊的代碼為:
let obj = reactive({
name: '姓名',
age: 18,
})
let { name, age } = toRefs(obj)
let work = toRef(obj, 'work')
const chang = () => {
name.value = '鉆石王老五'
age.value++
console.log('work', work.value)
work.value = '程序媛'
}5、toRaw
將響應(yīng)式對象轉(zhuǎn)為原始對象。做一些不想被監(jiān)聽的事情,從 ref 或 reactive 得到原始數(shù)據(jù)。
修改原響應(yīng)式數(shù)據(jù)時(shí),toRaw 轉(zhuǎn)換得到的數(shù)據(jù)會(huì)被修改,視圖也會(huì)更新,如:
{{ obj.name }} ------- {{ obj.age }}
{{ newObj }}
如果修改 toRaw 得到的原始數(shù)據(jù),原數(shù)據(jù)也會(huì)被修改,但是視圖不更新。如:
{{ obj.name }} ------- {{ obj.age }}
{{ newObj }}
當(dāng)前名稱:Vue3 的 Ref、IsRef、ToRef、ToRefs、ToRaw 詳細(xì)介紹
網(wǎng)頁網(wǎng)址:http://m.5511xx.com/article/cojhcho.html


咨詢
建站咨詢
