纯js实现v-model

142 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <input type="text" name="input" v-model="{{name}}"><br/>
    <p>{{name}}</p>
  </div>
  <script src="vm.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
          name: '大白鑫'
      }
    })
    
  </script>
</body>
</html>

class Vue {
  constructor(options) {
    this.el = document.querySelector(options.el)
    this._data = options.data
    this.dep = {}
    this.initData()
    this.initDom()

  }

  initDom() {
    let childNodes = this.el.childNodes
    const _this = this
    for(let item of childNodes){
      console.log('child', item)
      if(item.nodeType === 1){
        const value = item.getAttribute('v-model')
        if(value){
          const modelName = value.match(/\{\{(.+?)\}\}/)[1]
          item.value = _this.data[modelName]
          item.addEventListener('input', function (e) {
            _this.data[modelName] = e.target.value
            console.log('aaaa', _this.data[modelName])
          })
        }
      }
      if(item.childNodes.length != 0){
        const value = item.childNodes[0].data.trim()
        const modelName = value.match(/\{\{(.+?)\}\}/)
        if(modelName){
          console.log('sssss', modelName)
          item.innerHTML = this.data[modelName[1]]
          this.dep[modelName[1]] = item
        }
      }
    }
  }

  initData() {
    this.data = {}
    let _this = this
    for(let key in _this._data){
      Object.defineProperty(_this.data, key, {
        set(newValue) {
          _this._data[key] = newValue
          console.log('setProperty', _this.dep[key])
          if(_this.dep[key]) {
            _this.dep[key].innerHTML = newValue
          }          
        },
        get(){
          return _this._data[key]
        }
      })
    }
    this.data['name'] = '11'
  }
}```