How Vue Hooks Work Simple Example

This is a simple example to demonstrate the Vue hooks reactive system with the value function

by darkylmnx

HTML

<div id="app">
  <p></p>
  <button onclick="increment()">add +1</button>
</div>

JavaScript

// Implementation

const { value, renderTag, register }  = new MyCustomVue()

const $tag = document.querySelector('p')

let count = value(0)

register(() => renderTag($tag, count))

window.increment = () => count.value++






// NOW HERE IS THE MAGIC CODE !

function MyCustomVue() {
  let renderer

  this.register = function(callback) {
    renderer = callback
    renderer()
  }

  this.renderTag = function(tag, value) {
    tag.textContent = value
  }

  this.value = function(initialValue) {
    function O() {
      Object.defineProperty(this, 'value', {
        set(changedValue) {
          initialValue = changedValue
          renderer()
        },
        get() {
          return initialValue
        }
      })
    }

    O.prototype.toString = function() {
      return this.value
    }

    return new O()
  }
}