欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3響應式對象的api超全實例詳解

 更新時間:2023年05月08日 11:54:16   作者:野生切圖仔  
可以把數(shù)據(jù)變成響應式api的方法叫做響應式api,下面這篇文章主要給大家介紹了關(guān)于vue3響應式對象api的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

Ⅰ. ref、reactive ( 遞歸監(jiān)聽 )

import {ref,reactive} from 'vue';
setup() {
    const num =  ref(123);
    num.value = 456;
    const obj = reactive({num:123});
    obj.value = 456;
}
  • ref 對象 在 html 模板中會 自動添加 value ( ref 對象中__v_isRef:true 進行判斷的 )
  • ref 對象 => reactive( { value:0 } ) 底層自動轉(zhuǎn)換為 reactive
  • 最終 基本數(shù)據(jù) 類型采用 => (Object.defineProperty) ,引用數(shù)據(jù) 類型采用 => ( proxy 代理 )

Ⅱ. isRef、isReactive ( 判斷 )

import {isRef,isReactive} from 'vue';
setup() {
	const num = ref(123)
    console.log(isRef(num))  // => true
}
  • 用于判斷是否是 Ref 和 Reactive 創(chuàng)建的響應對象
  • 使用場景較少

Ⅲ. toRef 和 toRefs ( 解構(gòu) )

toRef (一個屬性)

import { toRef , reactive } from 'vue';
setup() {
	const obj = reactive({ width:10, height:20 })
    const width = toRef(obj,'width')
	return {
		width
	}
}

將一個響應對象的屬性,當作 響應對象 單獨拿出來 。

toRefs ( 所有 )

import { toRefs , reactive } from 'vue';
setup() {
	const obj = reactive({ width:10, height:20 })
    const { width, height }= toRefs(obj)
	return {
		width, height
	}
}

將多個或所有屬性,拿出來 且還是響應對象,一般在返回的時候一次性全部導出 ??

import { toRefs , reactive } from 'vue';
setup() {
	const obj = reactive({ width:10, height:20 })
	return {
		...toRefs(obj)
	}
}

Ⅳ. toRaw 、 markRaw ( 解除代理)

toRaw ( 不影響本身 )

import {toRaw} from 'vue';
setup(){
    const num1 =  ref(123)
    const num2 = toRaw(num1)
    console.log(num2 === 123)  //=>true
}
  • 不影響原數(shù)據(jù) ,相當于拷貝當前的值
  • 拷貝的值,不在是響應式對象

markRaw ( 添加 非響應對象 屬性 )

import { markRaw, reactive } from "vue";
setup(){
	const obj = reactive({ num:1 }); //讓數(shù)據(jù)無法被追蹤
	      obj.noUpdate = markRaw({num:1});
	function add() {
  		obj.num++;      // 頁面數(shù)據(jù) 會更新
  		obj.noUpdate.num++; //頁面數(shù)據(jù) 不會更新
	}
	return { obj , add }
}
  • 通過 markRaw 添加的值 => 其中的屬性變化,頁面不會監(jiān)聽的到
  • 用于添加搞定的參數(shù),不會發(fā)生不會的 ( 從而節(jié)約資源 )

Ⅴ. unref ( 拷貝 )

const aaa = ref('abc');
const bbb = unref(aaa); 
  • 相當于 bbb = isRef(aaa) ? aaa.value : aaa 的語法糖
  • 可以用于拷貝

Ⅵ. shallowRef 、shallowReactive( 非遞歸監(jiān)聽 )

shallowRef 、shallowReactive(非遞歸監(jiān)聽)

import {shallowRef,shallowReactive} from 'vue';
setup(){
	const  obj1 = shallowRef({a:1,b:{c:2})
	const  obj2 = shallowReactive({a:1,b:{c:2})
	obj1.value.a = 2  //頁面未更新
	obj2.b.c = 3  //頁面未更新
}
  • obj1 (shallowRef)=> 只監(jiān)聽第一層( value 的值,不監(jiān)聽a、b、c、d 的值)
  • obj2 (shallowReactive)=> 只監(jiān)聽第一層( a、b 的值,不監(jiān)聽 c 的值)

Ⅶ. triggerRef (強制更新)

import {triggerRef, shallowRef} from 'vue';
setup(){
	const  obj1 = shallowRef({a:1,b:{c:2})
    obj1.value.a = 2 //頁面沒有發(fā)生更新,因為只監(jiān)聽value第一層
	triggerRef(obj1);   // 強制更新

非遞歸監(jiān)聽,只監(jiān)聽首層 ,消耗的資源??;配合 triggerRef 強制更新 => 性能要大于 > 直接使用 (ref 和 reactive)

總結(jié)

到此這篇關(guān)于vue3響應式對象的api的文章就介紹到這了,更多相關(guān)vue3響應式對象api內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論