专业的编程技术博客社区

网站首页 > 博客文章 正文

一起学习vue3Ts-ref全家桶(vue3.0全家桶最全入门指南)

baijin 2024-10-04 13:25:23 博客文章 4 ℃ 0 评论

ref:ref定义字符串类型

// typeScript 中 type 关键字(可以给一个类型定义一个名称)多用于符合类型
//通过 类型别名, 给 string 换个名字 ,则 str0 为 string
type str0 = string
//ref指定 str0(字符串)类型
const stringValue0 = ref<str0>('abc')

Ref:Ref接受ref定义字符串类型

//Ref 为 ref 的返回值,通过类型别名 将 Ref<string> ,定义为 str,则stringValue 接收的类型为str
type str = Ref<string>
const stringValue: str = ref('abc')

泛型定义类型

//  参数 T 表示,传入的类型,如 number
type str2<T> = Ref<T>
const anyValue: str2<number> = ref(1111)

isRef:判断是否是 ref

//是 ref 类型返回 true , 否则返回 false
console.log( isRef(stringValue) )

ref:默认可以深层次监听

(1)type实现

//规范制定类型 
type extType = {
  sex: string
}
type jsonMap = {
  name: string
  age: number | string
  ext: extType
}
//ref 深层次
const stringValue2 = ref<jsonMap>({ name: 'tom', age: 18, ext: { sex: '男' } })

const onChange = () => {
  stringValue2.value.ext.sex = stringValue2.value.ext.sex === '女' ? '男' : '女'
}

(2)interface定义

//相同的 名字会合并
interface extType {
  sex: string
}
interface jsonMap {
  name: string
}
interface jsonMap {
  age: number | string
}
interface jsonMap {
  ext: extType
}
//ref 深层次
const stringValue2 = ref<jsonMap>({ name: 'tom', age: 18, ext: { sex: '男' } })

const onChange = () => {
  stringValue2.value.ext.sex = stringValue2.value.ext.sex === '女' ? '男' : '女'
}

shallowRef:浅层次监听

//shallowRef浅层次监听,sex 属性值无法监测到变化,注意 ref 和 shallowRef,不要一起出现,否则 shallowRef 会受 ref 影响
const stringValue3 = shallowRef<jsonMap>({
  name: 'tom',
  age: 18,
  ext: { sex: '男' }
})

const onChange3 = () => {
  //修改值后无法监听到变化
  stringValue3.value.ext.sex = stringValue3.value.ext.sex === '女' ? '男' : '女'
}

triggerRef :强制更新

//在浅层次shallowRef定义,再调用强制更新也能触发监听
const stringValue4 = shallowRef<jsonMap>({
  name: 'tom',
  age: 18,
  ext: { sex: '男' }
})
const onChange4 = () => {
  stringValue4.value.ext.sex = stringValue4.value.ext.sex === '女' ? '男' : '女'
  //使用强制更新后,浅层次更新则变为深层次更新,ref实际上也是调用 强制更新
  triggerRef(stringValue4)
}


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表