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的mvvm库 #57

Open
lizhongzhen11 opened this issue Dec 11, 2019 · 0 comments
Open

模拟实现一个类似vue的mvvm库 #57

lizhongzhen11 opened this issue Dec 11, 2019 · 0 comments
Labels
js基础 Good for newcomers

Comments

@lizhongzhen11
Copy link
Owner

lizhongzhen11 commented Dec 11, 2019

代码地址:

https://github.com/lizhongzhen11/mvvm/blob/master/Mvvm.js

参考链接:

  1. https://github.com/DMQ/mvvm
  2. https://juejin.im/post/5abdd6f6f265da23793c4458
  3. https://github.com/codeyu/mini-mvvm

心路历程

从第一版到第三版都是我自己根据结果去猜想实现,当然,期间确实有的坑趟不过去,只能看文章找思路。但是,最终我写出来的还是有重大bug,所以最后一个版本基本上就是照着网上代码去修改,也踩了不少坑。我用的是Proxy不是Object.defineProperty,区别还是有的,这样实践也算是基本理解了。

断断续续三天呢!

具体过程看代码里面的注释吧,太多了,真正的从0到1,从完全不懂的小白到最终写出来的一步步过程。

用到的技能点

  1. 利用es6的 proxy 进行数据拦截监听
  2. createDocumentFragment:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment
  3. appendChild:https://developer.mozilla.org/zh-CN/docs/Web/API/Node/appendChild
  4. cloneNode:https://developer.mozilla.org/zh-CN/docs/Web/API/Node/cloneNode , 新规范有所更改,不传deep默认不拷贝后代元素
  5. Node.nodeType:https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
  6. RegExp.$1-$9:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n
  7. replace:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace#%E6%8C%87%E5%AE%9A%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0
  8. Element.attributes:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/attributes

遇到的问题

  1. proxy代理数组对象时,set必须返回 true,不然使用数组api会报错见:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set
  2. 模板中变量用 {{}} 来包裹,正则也只判断 {{}} 中的变量并渲染
  3. 文本如果是 文字 + {{变量}} 形式,应该用 replace 来替换!!!
  4. 使用 Dep + Watcher 联合组成发布订阅,只有实例化 Watcher 时,才会添加订阅
  5. replace + reduce 进行替换,代码非常简洁优美
  6. node替换时,通过 this.mvvm.initMounted 仅在初始化时实例化Watcher,以后更新时不用实例化,减少性能损耗,尤其双向绑定时,没有这个限制的话,卡死了!!!嗯,我踩的坑,难怪我一开始不明白人家的代码为何要有这个,还是实际敲才有用
  7. v-model 绑定的输入框,输入中文时,输入不了,且第一个字母会出现两个。经过不断调试,发现有个 Watcher 里的 exp 是 text,这个是v-model输入框才有的,仔细看了下代码,我没有把 new Watcher 放在 if (name === 'v-model') {} 里面。。。。。。
  8. 遇到两个{{}}连在一起时,我不知道如何解析了,看了人家的代码,也没看出什么,后来仔细查,发现正则不一样,加个g全局匹配就好了。哈哈哈哈哈,正则不会呢。。。

打算

打算加上虚拟dom和diff算法,这两个我都不会,不过肯定是要趟过去的!

@lizhongzhen11 lizhongzhen11 added the js基础 Good for newcomers label Dec 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js基础 Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant