reactive
<template>
<h1>{{ obj.count }}</h1>
<h1>{{ shallowObj }}</h1>
<button @click="change">change</button>
</template>
<script setup lang="ts">
import { reactive, readonly, shallowReactive } from 'vue'
// const obj = reactive(0) // reactive必须使用引用类型,使用基础类型报错
let obj = reactive({
count: 5
})
let arr = reactive(['5'])
let readObj = readonly(obj)
let shallowObj = shallowReactive({
type: {
name: {
age: 1
}
}
})
const change = () => {
// const newObj = { count: 6}
// reactive 是proxy对象,不需要通过.value取值,同时不能直接赋值,否则丧失双向绑定
// obj = newObj
// 修改方法
obj.count = 6 // 可以通过直接过去属性值赋值
arr.push('6') // 通过数组方法也可以赋值
// console.log(obj,arr) Proxy{count:6}; ['5','6']
// readObj.count = '7' // 报错,readonly只能读,不能修改值
// obj.count = 7
// 修改readonly的数据:
// console.log(readObj) Proxy({count:7}) readonly会受原变量影响,当obj被修改时readObj会同步被修改
// shallowObj.type.name.age = 2 // 响应式无法生效
// shallowObj.type.name = { age: 2} // 响应式无法生效
//只能影响到第一层的属性值,同shallowRef只能影响到.value,也同样当有reactive赋值的时候会同时被刷新的特性
shallowObj.type = { name:{ age: 2} }
}
</script>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
浙公网安备 33010602011771号