一、ref和reactive使用泛型的约束
1.ref
<template>
<div
style="
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<h1>ref的使用</h1>
<div class="">ref:{{ testRef }}</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import type { Ref } from 'vue';
const testRef = ref<string>('ref的使用');
const a = ref(''); //根据输入参数推导字符串类型 Ref
//列:a.value = "通过类型推导只能写字符串"
const b = ref<Array<string>>([]); //通过泛型约束这个b只能是字符串的数组
//列:b.value = ['aaa', 'bbb'];
const c: Ref<Array<string>> = ref([]); //声明类型 Ref泛型约束这个b只能是字符串的数组
//列:c.value = ['aaa', 'bbb'];
</script>
<style lang="scss" scoped></style>
2.reactive
- 返回对象的响应式的对象
const obj = reactive({ a: 'a', b: 'b' }); //通过ts的类型推断直接约束好了类型
const arr = reactive([1, 2]); //数组,其实结果还是对象
//reactive定义和ref不同,ref返回的是Ref<T>类型,reactive不存在Reactive<T>
type typObj = {
name: string;
age: number;
};
const obj1 = reactive<typObj>({ name: 'aa', age: 18 }); //obj1 类型为: { name: string; age: number; }
3.isRef、isReactive
- isRef 检查值是否为一个 ref 对象(isReactive同例)
console.log('是否是ref类型', isRef(testRef)); //是否是ref类型 true
4.toRef
- toRef 为源响应式对象上的某个元素 新创建一个 ref()
type toRefTest = {
name: string;
px: string;
};
const toRefTest = ref<toRefTest>({
name: 'aa',
px: 'bb'
});
const toRefName = toRef(toRefTest.value, 'name');
console.log(toRefTest.value); //Proxy(Object) {name: 'aa', px: 'bb'}
console.log(toRefName.value); //aa
5.toRefs
- toRefs 将响应式对象Proxy 转换为普通对象,每一个元素都变成原始的ref对象
type toRefTest = {
name: string;
px: string;
};
const toRefTest = reactive<toRefTest>({
name: 'aa',
px: 'bb'
});
const toRefName = toRefs(toRefTest);
console.log(toRefName); //{name: ObjectRefImpl, px: ObjectRefImpl}
6.toRaw
- toRaw 返回原始对象
type toRefTest = {
name: string;
px: string;
};
const toRefTest = reactive<toRefTest>({
name: 'aa',
px: 'bb'
});
const toRefName = toRaw(toRefTest);
console.log(toRefName); //{name: 'aa', px: 'bb'}
7.shallowRef
- 与ref不同,shallowRef修改深层属性时,并不会更新视图
- 因为ref方法会递归遍历对象的所有属性,使所有属性都具备响应性,所以,当对象很复杂且庞大时,过多的监听会导致性能上的损耗
//深度的对象
const msg = shallowRef({
foo: {
foo1: {
foo2: {
foo3: {
name: '张三'
}
}
}
}
});
//跟新数据
const upShallowRef = () => {
//shallowRef也有一层的ref的包装对象,所以也需要.value进行赋值
msg.value.foo.foo1.foo2.foo3.name = '深度更新';
console.log('msg---', msg);
};
- 结果
- 数据跟新了,页面没有跟新
8.triggerRef
- 手动更新shallowRef变量的视图。
const upShallowRef = () => {
msg.value.foo.foo1.foo2.foo3.name = '深度更新';
triggerRef(msg);//进行视图的跟新
console.log('msg---', msg);
};