1. ref 支持所有类型,reactive 只支持应用类型 Array、Object、Map、Set、Date、Function
2. ref 取值 赋值 都需要加 .value reactive 取值 赋值 不需要加 .value
3. reactive 是proxy 代理对象 不能直接赋值 否则会破坏响应式对象
<template>
<div>
<ul v-for="item in list" :key="item">
<li>{{ item }}</li>
</ul>
<button @click.prevent="add">提交</button>
</div>
</template>
<script setup lang='ts'>
import { ref,reactive } from 'vue'
let list = reactive<string[]>([])
const add = () => {
setTimeout(() => {
let res = ['apex','cs','lol']
list.push(...res)
console.log(list);
}, 1000);
}
</script>
<style scoped>
</style>
- 解决方案2:添加一个对象,把数组作为一个属性去解决
<div>
<ul v-for="item in list.arr" :key="item">
<li>{{ item }}</li>
</ul>
<button @click.prevent="add">提交</button>
</div>
</template>
<script setup lang='ts'>
import { ref,reactive } from 'vue'
//解决方案2
let list = reactive<{arr:string[]}>({
arr:[]
})
const add = () => {
setTimeout(() => {
let res = ['apex','cs','lol']
list.arr = res
console.log(list);
}, 1000);
}
</script>
<style scoped>
</style>
4. readonly 只读属性
<template>
<div>
<button @click="show">查看</button>
</div>
</template>
<script setup lang='ts'>
import { ref,reactive,readonly } from 'vue'
let obj = reactive({name:'zhangsan'})
const read = readonly(obj)
const show = () => {
read.name = 'lisi'
obj.name = 'lisi'
console.log(obj,read)
}
</script>
<style scoped>
</style>
5. shallowReactive 浅层次响应数据变化
<template>
<div>
<p>{{obj}}</p>
<button @click="edit">修改</button>
</div>
</template>
<script setup lang='ts'>
import { ref,reactive,readonly,shallowReactive } from 'vue'
const obj = shallowReactive({
foo:{
bar:{
num:1
}
}
})
const edit = () => {
obj.foo.bar.num = 123
console.log(obj)
}
</script>
<style scoped>
</style>