字符串匹配与动态绑定Set/Get

字符串匹配与动态绑定Set/Get

<script>
      let template = `
      <template>
        <div>
          {{ emp.name }}
          {{ emp.age }}
          {{ emp.Friends_list }}
          {{ emp.Girlfriends }}
        </div>
      </template>
      `;

      let emp = {
        name: "kyle",
        age: 19,
        Friends_list: [
          {
            name: "杰杰",
            age: 24,
          },
          {
            name: "老刘",
            age: 24,
          },
          {
            name: "明明",
            age: 24,
          },
          {
            name: "小新",
            age: 24,
          },
        ],
        Girlfriends: [
          {
            name: "花花",
            age: 21,
          },
        ],
      };
      function deepBindSet(obj) {
        let newObj = {};
        if (Array.isArray(obj)) newObj = [];
        for (const key in obj) {
          if (obj[key] instanceof Object || 
              obj[key] instanceof Array) {
            newObj[key] = deepBindSet(obj[key]);
          } else {
            console.log(obj[key]);
            Object.defineProperty(newObj, "_" + key, 			{
              writable: true,
              value: obj[key],
            });
            Object.defineProperty(newObj, key, {
              get() {
                return this["_" + key];
              },
              set(nV) {
                console.log(key, nV);
                this["_" + key] = nV;
              },
            });
          }
        }
        return newObj;
      }

      let nv = deepBindSet(emp);
      nv.name = "亮亮";
      // 过滤模板中的关键字
      let args = template.match(/\{[^\}]+\}\}/gi);

      args = args.map((item, index) => {
        let str = item.slice(2, -2).trim();
        let data = eval(str);
        console.log(data);
        return data;
      });
      console.log(args);
</script>
上一篇:Solon Web 开发,十二、统一的渲染控制


下一篇:LayUI点击表格表头排序、拖拽表格列、以及JS驼峰和下划线互转