基本用法 ref
<template>
<h1>{{data.name}}</h1>
</template>
<script setup lang="ts">
import {ref} from "vue"
const data = ref({name:'zhangsan'})
data.name.value = "lisi"
</script>
使用泛型
<template>
<h1>{{data.name}}</h1>
</template>
<script setup lang="ts">
import {ref} from "vue"
import type {Ref} from "vue"
type Data = {name:string}
var data:Ref<Data> = ref({name:'zhangsan'})
</script>
使用复杂的 interface
<template>
<h1>{{data.name}}</h1>
</template>
<script setup lang="ts">
import {ref} from "vue"
import type {Ref} from "vue"
interface Data {
name:string
}
var data:Ref<Data> = ref({name:'zhangsan'})
</script>
浅层响应式 shallowRef
用法同 ref , shallowRef 不会更新视图,即不会调用 triggerRef 而 Ref 函数每次变化都会触发 triggerRef;
<template>
<h1>{{data.name}}</h1>
</template>
<script setup lang="ts">
import {shallowRef} from "vue"
const data = shallowRef<any>({name:'zhangsan'})
setTimeout(()=>{data.value.name='lisi',3000) // 视图不会更新
</script>
强制更新 triggerRef
<template>
<h1>{{data.name}}</h1>
<h1>{{data2.name}}</h1>
</template>
<script setup lang="ts">
import {ref,shallowRef,triggerRef} from "vue"
const data = shallowRef<any>({name:'zhangsan'})
setTimeout(()=>{
data.value.name="lilsi"
triggerRef(data)
},3000) // 视图不会更新
</script>