index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { observe } from '../observer/index'
  2. import Watcher from '../observer/watcher'
  3. import { h, patch } from '../vdom/index'
  4. import { nextTick, isReserved, query } from '../util/index'
  5. export default function Component (options) {
  6. this.$options = options
  7. this._data = options.data
  8. this._el = query(options.el)
  9. this._el.innerHTML = ''
  10. Object.keys(options.data).forEach(key => proxy(this, key))
  11. if (options.methods) {
  12. Object.keys(options.methods).forEach(key => {
  13. this[key] = options.methods[key].bind(this)
  14. })
  15. }
  16. this._ob = observe(options.data)
  17. this._watchers = []
  18. this._watcher = new Watcher(this, options.render, this._update)
  19. this._update(this._watcher.value)
  20. }
  21. Component.prototype._update = function (vtree) {
  22. if (!this._tree) {
  23. patch(this._el, vtree)
  24. } else {
  25. patch(this._tree, vtree)
  26. }
  27. this._tree = vtree
  28. }
  29. function proxy (vm, key) {
  30. if (!isReserved(key)) {
  31. Object.defineProperty(vm, key, {
  32. configurable: true,
  33. enumerable: true,
  34. get: function proxyGetter () {
  35. return vm._data[key]
  36. },
  37. set: function proxySetter (val) {
  38. vm._data[key] = val
  39. }
  40. })
  41. }
  42. }
  43. Component.prototype.__h__ = h
  44. Component.nextTick = nextTick