前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >模拟reactive/ref/shallowReactive/shallowRef

模拟reactive/ref/shallowReactive/shallowRef

作者头像
刘嘿哈
发布2022-10-25 14:10:06
4540
发布2022-10-25 14:10:06
举报
文章被收录于专栏:js笔记

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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档