模拟reactive/ref/shallowReactive/shallowRef

2022-10-25 14:10:06 浏览数 (2)

ref基于reactive,shallowRef基于shallowReactive

代码语言:javascript复制
<template>
 <div>{{ state.a }}</div>
 <div>{{ state.gf.b }}</div>
 <div>{{ state.gf.f.c }}</div>
 <div>{{ state.gf.f.s.d }}</div>
 <button @click="myFn">改变</button>
</template>

<script>
// shallowReactive,shallowRef
function shallowRef(value) {
 return shallowReactive({ value });
}
function shallowReactive(obj) {
 return new Proxy(obj, {
   get(obj, key) {
     //返回指定值
     const res = Reflect.get(obj, key);
     return res;
   },
   set(obj, key, val) {
     //设置指定值
     const res = Reflect.set(obj, key, val);
     console.log("更新ui");
     return res;
   },
 });
}
function ref(value){
 return reactive({value})
}
function reactive(obj) {
 if (typeof obj !== "object") {
   console.warn("您给的不是一个对象");
 } else {
   if (obj instanceof Array) {
     obj.forEach((item, index) => {
       if (typeof item == "object") {
         obj[index] = reactive(item);
       }
     });
   } else {
     for (var key in obj) {
       let item = obj[key];
       if (typeof item === "object") {
         obj[key] = reactive(item);
       }
     }
   }
   return new Proxy(obj, {
     get(obj, key) {
       //返回指定值
       const res = Reflect.get(obj, key);
       return res;
     },
     set(obj, key, val) {
       //设置指定值
       const res = Reflect.set(obj, key, val);
       console.log("更新ui");
       return res;
     },
   });
 }
}
export default {
 setup() {
   let state = reactive({
     a: 1,
     gf: {
       b: 2,
       f: {
         c: 3,
         s: {
           d: 4,
         },
       },
     },
   });
   let list = [
     { name: "tom", age: 19, sex: "男" },
     { name: "jarry", age: 19, sex: "男" },
     { name: "susan", age: 19, sex: "男" },
   ];
   let peple=reactive(list);
   console.log(state);
   let count=ref(22)
   console.log(count)
   function myFn() {
     // state = {
     //   a: "a",
     //   gf: {
     //     b: "b",
     //     f: {
     //       c: "c",
     //       s: {
     //         d: "d",
     //       },
     //     },
     //   },
     // };
     // state.a='a'
     // state.gf.b='b'
     // state.gf.f.c='c'
     // state.gf.f.s.d='d '
     // console.log(state);
     // peple[0].name='好好'
     // peple[0].age=100
     count.value=22222
     console.log(count.value)
   }
   

   return { state, myFn };
 },
};
</script>

<style  scoped>
</style>
ref

0 人点赞