[关闭]
@xiaoqq 2016-08-29T12:07:49.000000Z 字数 1839 阅读 997

Vue学习笔记——自己编写一个MVVM框架

Vue


一、构造函数的实现

Vue构造函数传入option参数,主要属性有:

  1. function Vue(option) {
  2. this.option = option || {};
  3. this._data = option.data;
  4. this._initData(this._data);
  5. }
  6. Vue.prototype._initData = function(data) {
  7. Object.keys(data).forEach(key => {
  8. this._proxy(key);
  9. });
  10. };
  11. Vue.prototype._proxy = function(key) {
  12. var self = this;
  13. Object.defineProperty(this, key, {
  14. get: function proxyGetter() {
  15. return self._data[key];
  16. },
  17. set: function proxySetter(newVal) {
  18. self._data[key] = newVal;
  19. }
  20. })
  21. };

二、实现观察者Observer

Vue中需要将所有属性递归地转成观察者Observer,当其值改变的时候,可以通知Wacher,并且执行其update函数。

Observer为构造函数,传入参数value,原型中拥有以下方法:

还有两个辅助函数:

  1. function Observer(value) {
  2. this.value = value;
  3. this.walk(value);
  4. }
  5. Observer.prototype.walk = function(value) {
  6. var that = this;
  7. Object.keys(value).forEach(function(key) {
  8. that.convert(that.value, key, that.value[key]);
  9. });
  10. }
  11. Observer.prototype.convert = function(vm, key, value) {
  12. defineReactive(vm, key, value);
  13. }
  14. function observer(value) {
  15. if (!value || typeof value !== 'object') {
  16. return;
  17. }
  18. return new Observer(value);
  19. }
  20. function defineReactive(vm, key, value) {
  21. var dep = new Dep(); //每一个value都有watcher管理器,存放在闭包中
  22. var childOb = observer(value);
  23. Object.defineProperty(vm, key, {
  24. enumerable: true,
  25. configurable: true,
  26. get: function getReactive() {
  27. console.log('get value');
  28. if (Dep.target) {
  29. dep.addSub(Dep.target);
  30. }
  31. return value;
  32. },
  33. set: function setReactive(newVal) {
  34. console.log('set value');
  35. if (newVal === value) {
  36. return;
  37. }
  38. childOb = observer(newVal);
  39. value = newVal;
  40. dep.notify();
  41. }
  42. })
  43. }

三、实现订阅者Watcher

四、编译和指令

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注