ref、reactive
·
一、ref
区别:
1、isRef判断是不是ref对象返回 boolean值
2、shallowRef判断是不是ref对象 返回boolean值
3、ref深层次响应 shallowRef浅层次(value之后的赋值不生效)
4、ref不能和shallowRef一起使用,会造成shallowRef的视图更:
<template>
<div>
{{ man.name }}
</div>
<input type="text" v-model="man.name" name="" id="">
</template>
<script setup lang='ts'>
import { ref} from 'vue'
type M = {
name: string
}
const man: Ref<M> = ref({ name: '小琳' })
</script>
<style scoped></style>
二、isRef
const man: Ref<M> = ref({ name: '小琳' })
console.log(isRef(man)); //true
三、shallowRef
<template>
<div>
{{ man2.name }}
</div>
<button @click="change">修改</button>
</template>
<script setup lang='ts'>
import {shallowRef } from 'vue'
const man2 = shallowRef({ name: '小哈哈' })
const change = () => {
man2.value.name = "我被影响了"
console.log(man2);
}
</script>
<style scoped></style>
此时其实修改了值但是页面的数据是未变化的

四、triggerRef
<template>
<div>
{{ man2.name }}
</div>
<button @click="change">修改</button>
</template>
<script setup lang='ts'>
import {triggerRef} from 'vue'
const man2 = shallowRef({ name: '小哈哈' })
const change = () => {
man2.value.name = "我被影响了"
triggerRef(man2)
console.log(man2);
}
</script>
<style scoped></style>
此时页面的数据也发生了更改
五、customRef
<template>
<div>
{{ obj }}
</div>
</template>
<script setup lang='ts'>
import {customRef,nextTick} from 'vue'
function MyRef<T>(value: T) {
let timer: any
return customRef((track, trigger) => {
return {
get() {
track()
return value
},
set(newVal) {
// 防抖
clearTimeout(timer)
timer = setTimeout(() => {
value = newVal
console.log('触发了');
timer = null
trigger()
}, 500)
}
}
})
}
const obj = MyRef('小林')
const dom = ref<HTMLDivElement>()
nextTick(() => {
console.log(dom.value?.innerText);
})
</script>
<style scoped></style>
此时页面显示小林
六、toRef、toRaw
1、 toRef只能修改响应式对象的值 非响应式视图不变化 应用场景 useDemo(toRef(man,‘name’))
2、 toRefs解构取值为响应式
3、 toRaw当对象不做响应式的话,变成基本的变量
const man = reactive({ name: '小曼', age: 22, like: '小崔' })
console.log(man, toRaw(man));

const man = reactive({ name: '小曼', age: 22, like: '小崔' })
const a = toRef(man, "name")
console.log(a, "a");

七、reactive、shallowReactive
shallowReactive和shallowRef一样的问题(修改一层代码(浅层响应),和reactive写在一起被reactive影响)
type X = {
name: string,
id: number
}
let list = reactive<X[]>([{ name: '你好', id: 0 }, { name: '你好1', id: 1 }, { name: '你好2', id: 2 }])
怎么解决reactive为proxy代理对象不能直接赋值?
解决方案:
1、数组使用push解构赋值
2、添加一个对象,把数组作为一个对象解决
总结
ref和reactive的区别:
1、ref支持所有类型 ,reactive 支持引用类型、Array、Object、Map、Set
2、ref需要通过.value属性来访问其实际值;而reactive可以直接访问其属性或调用其方法。
3、ref能直接赋值,而reactive为proxy代理对象不能直接赋值,否则破坏响应式对象
let list = reactive<X[]>([{ name: '你好', id: 0 }, { name: '你好1', id: 1 }, { name: '你好2', id: 2 }])
list = [{ name: '你好4', id: 4 }] //赋值不成功
4、watch()默认情况下只监视ref()的直接.value更改,而对reactive()对象进行深度监视。
更多推荐
所有评论(0)