美文网首页
vue 必备知识

vue 必备知识

作者: ynwshy | 来源:发表于2020-08-11 12:06 被阅读0次

    vue 3.0

    Object.defineProperty()

    console.log("----------------");
    console.log("vue3 核心 代理  ");
    console.log("----------------");
    console.log("\n\n");
    
    function trigger(value) {
      console.warn("触发视图更新 变量改变了 :", value);
    }
    
    function reactive(target) {
      const handlers = {
        set(target, key, value, receiver) {
          console.warn("handlers -> set ", target, key, value, receiver);
          trigger(key, value);
          return Reflect.set(target, key, value, receiver);
        },
        get(target, key, receiver) {
          console.warn("handlers -> get ", target, key, receiver);
          return Reflect.get(target, key, receiver);
        },
        deleteProperty() {
          console.warn("handlers -> set ");
          return Reflect.deleteProperty(target, key, receiver);
        },
      };
      let observed = new Proxy(target, handlers);
      return observed;
    }
    
    let obj = { name: "hy" };
    console.log("obj        : ", obj);
    let proxy = reactive(obj);
    console.log("obj 代理給 proxy 对象");
    console.log("proxy      : ", proxy);
    
    console.log("\n-------- get --------");
    console.log("obj.name   : ", obj.name);
    console.log("proxy.name : ", proxy.name);
    
    console.log("\n-------- set --------");
    proxy.name = "ynwshy";
    
    console.log("obj.name   : ", obj.name);
    console.log("proxy.name : ", proxy.name);
    
    
    Snipaste_2020-08-11_12-06-13.png

    vue 2.0

    Object.defineProperty()

    
    let me = { money: "我的100" };
    let boss = "";
    
    console.log("me.money  :", me.money); // "我的都是老板的"
    console.log("boss      :", boss); // "我的都是老板的"
    
    Object.defineProperty(me, "money", {
      get: function () {
        console.warn("get: ");
        return boss;
      },
      set: function (newVal) {
        console.warn("set: ", newVal);
        boss = newVal;
      },
    });
    
    
    console.log("\n-------- get --------");
    
    console.log("me.money  :", me.money); 
    console.log("boss      :", boss);
    
    console.log("\n-------- set --------");
    
    me.money = "我的10";
    console.log("me.money  :", me.money); // "我的都是老板的"
    console.log("boss      :", boss); // "我的都是老板的"
    

    相关文章

      网友评论

          本文标题:vue 必备知识

          本文链接:https://www.haomeiwen.com/subject/opgkzxtx.html