美文网首页
vue-observe

vue-observe

作者: 田帅奇 | 来源:发表于2018-09-03 19:02 被阅读0次

    vue可以实现递归监听,因为变量地址引用的关系,还是闭包大法好,总觉得有点hack的感觉呢!

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
      <script>
        let data = {
          name: 'zs',
          age: 18,
          like: {
            walk: 'walk',
            play: {
              ball: 'baskball'
            },
            go: {
              school: {
                where: 'top'
              }
            }
          }
        }; 
        var _data = {};
        observe(data);
        function observe (data) {
          _data = data;
          Object.keys(data).forEach(k => {
            convert(k, data[k])
          });
        }
        function convert (k,v) {
          defineReactive(_data, k ,v)
        }
        function defineReactive (data, k, v) {
          if (typeof v === 'object') {
            observe(v);
          }
          Object.defineProperty(data, k, {
            get: function () {
              console.log('listen get');
              return v;
            },
            set: function (nv) {
              console.log('listen set');
              if (nv === v) return
              v = nv;
              observe(nv);
            }
          });
        }
        console.log(data.like.go);
        data.like.go = 1111;
        console.log(data.like.go);
        console.log(data.like);
      </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:vue-observe

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