扬州网站建设小程序,网易企业邮箱收件服务器主机名,免费写作文网站,参加sem培训一、 reactive 和ref 都是深层响应式对象: 就是不管对象有多少层#xff0c;修改此对象任一属性都会响应式处理 shallowReactive 和shallowRef 浅层响应式对象: 只会修改第一层对象#xff0c;修改此对象第一层属性#xff0c;视图会有同步变化#xff0c;非第一层#xf…一、 reactive 和ref 都是深层响应式对象: 就是不管对象有多少层修改此对象任一属性都会响应式处理 shallowReactive 和shallowRef 浅层响应式对象: 只会修改第一层对象修改此对象第一层属性视图会有同步变化非第一层数值会变视图不会变。
例如有这样一个对象
{
id:1,name:张三,car:{price: 7000,color: red}
}
vue3中定义shallowReactive 对象后修改id。视图会同步变化如果修改的是car.price。视图不会变化除非先修改car.price 对象然后再修改id这时第一层对象触发会把这个对象更新。具体例子如下
script setup /*** reactive 和ref 都是深层响应式对象: 就是不管对象有多少层修改此对象任一属性都会响应式处理* shallowReactive 和shallowRef 浅层响应式对象:* * */import {reactive,ref,shallowReactive} from vue;const state reactive({id:1,name:张三,car:{price: 7000,color: red}});function updateStateId() {state.id;};function updateStatePrice() {state.car.price;};const stateRef ref({id:1,name:张三,car:{price: 7000,color: red}});function updateRefStateId() {stateRef.value.id;};function updateRefStatePrice() {//直接改非第一层数据视图不更新也就是多层级的数据是非响应式的stateRef.value.car.price;};const shallowstate shallowReactive({id:1,name:张三,car:{price: 7000,color: red}});function updateIdByShallowReactive() {shallowstate.id;};function updatePriceByShallowReactive() {//直接改非第一层数据视图不会更新也就是多层级的数据是非响应式的shallowstate.car.price;};function updatePriceAndIdByShallowReactive() {//直接改非第一层数据视图不会更新也就是多层级的数据是非响应式的shallowstate.car.price;//当修改了第一层数据也修改其他层数据此时会将此对象所有的数据都更新视图//原理当改变底层数据会触发该状态的监听器将此状态所有数据更新到视图中shallowstate.id;};/scripttemplatedivpreactive{{ state.id }}{{ state.car }}/pbutton clickupdateStateId更新reactive/buttonbutton clickupdateStatePrice更新reactiveprice/buttonpref{{ stateRef.id }}{{ stateRef.car }}/pbutton clickupdateRefStateId更新ref/buttonbutton clickupdateRefStatePrice更新ref price/buttonh4function updatePriceAndIdByShallowReactive() {br//直接改非第一层数据视图不会更新也就是多层级的数据是非响应式的brshallowstate.car.price;br//当修改了第一层数据也修改其他层数据此时会将此对象所有的数据都更新视图brshallowstate.id;br};/h4pshallowReactive{{ shallowstate.id }}{{ shallowstate.car }}/pbutton clickupdateIdByShallowReactiveshallowReactive更新id/buttonbutton clickupdatePriceByShallowReactiveshallowReactive更新car.price/buttonbutton clickupdatePriceAndIdByShallowReactiveshallowReactive更新car.price和id/button/div
/templatestyle scoped/style点击更新ref对象数据id 按钮id属性加1 点击更新ref对象数据car.pricecar.price属性加1 点击更新reactive对象数据id按钮id属性加1 点击更新reactive对象数据car.pricecar.price属性加1 点击更新shallowReactive对象属性idid属性加1 点击更新shallowReactive对象属性car.pricecar.price属性加1视图不更新。还是7000 点击更新shallowReactive对象属性car.price和idcar.price和id属性都加1并且shallowReactive视图更新。看到下图id加了1price 加了2。