<template> <h2>姓名:{{user.name}}</h2> <h2>姓名:{{user.age}}</h2> <h2>姓名:{{user.job.salsry}}k</h2> <button @click="user.name+='%'">修改姓名</button> <button @click="user.age++">修改年龄</button> <button @click="user.job.salsry+=10">修改薪水</button> <hr /> <button @click="addPosition">添加位置信息</button> <fieldset v-if="user.position"> <h3>省:{{user.position.province}}</h3> <h3>市:{{user.position.city}}</h3> <button @click="user.position!.province +='#'">修改省</button> <button @click="user.position!.city +='#'">修改市</button> </fieldset> </template> <script lang="ts"> type UserInfo={ name:string; age:number; job:{ salsry:number; } position?:{ province:string; city:string; } } import { customRef,reactive,markRaw,shallowReadonly,shallowReactive,ref,readonly,toRefs,shallowRef} from 'vue'; export default{ setup(){ //shallowReactive只处理最外层属性的响应式(浅相应),里层的薪水就修改不了 //shallowRef,将user对象替换成新的对象,改不了属性 //let user=shallowReactive let user:UserInfo=reactive({ name:"jack", age:20, job:{ salsry:30, }, }) //readonly可以转换refImpl类型的数据为只读 //user =readonly(user); //浅只读,内层不只读 //user=shallowReadonly(user); //toRaw可以将响应式对象变成普通对象 //普通对象与响应式对象是关联关系,非深拷贝 //当更新普通对象时,响应对象也会更新,但不会更新界面 //当更新响应式对象时,普通对象也会更新,会更新界面 function addPosition(){ //添加一个新的对象position,将该对象标记为非响应式对象 user.position= markRaw({ province:"广东", city:"珠海", }) } return {user,addPosition} } } </script>
标签:修改,对象,更新,学习,响应,user,Vue3,position From: https://www.cnblogs.com/zsbb/p/16846738.html