Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VUE源码学习(1)-vue核心内容简单实现1 #33

Open
iliuyt opened this issue Mar 11, 2019 · 0 comments
Open

VUE源码学习(1)-vue核心内容简单实现1 #33

iliuyt opened this issue Mar 11, 2019 · 0 comments

Comments

@iliuyt
Copy link
Owner

iliuyt commented Mar 11, 2019

知识点

  • 虚拟dom的使用createDocumentFragment,关机在于可以通过更改node的textContent来更新数据
  • 属性设置的使用defineProperty,如何通过defineProperty来设置getter 和 setter,这里非常重要
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Simple Vue</title>
</head>
<style>
  #app {
    text-align: center;
  }
</style>

<body>
  <div id="app">
    <p id="vdom">初始化中</p>
  </div>
</body>
<script>

  // 被监听的数据
  let data = { message: "" };

  // 虚拟dom集合
  let nodes = [];

  // 设置虚拟dom
  let el = document.querySelector("#app");
  const fragment = document.createDocumentFragment();
  let child = document.querySelector("#vdom");;
  fragment.appendChild(child)
  nodes.push(fragment.childNodes[0])
  el.appendChild(fragment)


  // 设置监听
  let watcher = {
    update() {
      // 更新dom
      nodes[0].textContent = data.message
    }
  };

  // 监听和分发集合
  let dep = {
    subs: [],
    notify() {
      this.subs.forEach(item => {
        item.update();
      })
    }
  }

  // 设置监听数据的getter和setter
  Object.defineProperty(data, 'message', {
    enumerable: true,
    configurable: true,
    get() {
      return this.value;
    },
    set(newVal) {
      // 如果值一样,不更新dom
      if (newVal === this.value) {
        return;
      }
      this.value = newVal;
      // 触发所有监听
      dep.notify();
    }
  });

  // 添加监听到集合中
  dep.subs.push(watcher)

  // 定时更新数据,更新dom
  setInterval(() => {
    data.message = "当前时间戳为:" + Date.now()
  }, 1000);
</script>

</html>
@iliuyt iliuyt changed the title VUE源码学习(1)-vue核心内容简单实现 VUE源码学习(1)-vue核心内容简单实现1 Mar 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant