自嗨小型vuejs

class Vue {
    
    
      constructor(options) {
    
    
        console.log(options)
        this.data = options.data
        console.log(this.data)
        console.log(this)
        this.template = options.template
        this.el = options.el
        this.observe(this.data)
        this.compile(this.el,this.template,this.data)
        this.parseHtml(this.template)
      }
      observe(obj) {
    
    
        if (obj instanceof Object) {
    
    
          Object.keys(obj).map(res => {
    
    
            this.define(obj, res, obj[res])
          })
        } else {
    
    
          return obj
        }
      }
      define(obj, key, value) {
    
    
        if (value instanceof Object) {
    
    
          this.observe(value)
        }
        Object.defineProperty(obj, key, {
    
    
          set: function (val) {
    
    
            if (value === val) return
            obj[key] === val
            console.log('set', key)
          },
          get: function () {
    
    
            console.log('get', value)
            return value
          }
        })
      }
      parseHtml (template) {
    
    
        var str = template;
        var pattern = /<(?:[^"'>]|"[^"]*"|'[^']*')*>/g;
        console.log(str.match(pattern))
        // 认怂了 ast标签节点语法树
      }
      compile (el,template,data) {
    
    
        var textReg = /\{\{((?:.|\n)+?)\}\}/g
        var text = template.match(textReg)
        var arr = []
        var actuality = []
        text.map((res,index) => {
    
    
          let result = res.match(/[(a-zA-Z) || (a-zA-Z.a-zA-Z)]+/g)[0]
          arr[index] = result
          // console.log(res)
          if (res === `{
     
     {
     
     ${
      
      result}}}`) {
    
    
            template = template.replace(/\{\{((?:.|\n)+?)\}\}/,data[result])
          }

        })
        console.log(arr)
        const dom = document.getElementById(el.split('#')[1])
        const html = document.createDocumentFragment()
        const div = document.createElement('div')
        div.innerHTML = template
        dom.appendChild(div)
        dom.appendChild(html)
      }
    }
    let obj = {
    
    
      a: 'hello',
      b: 'worldqw',
      c: {
    
    
        q: 12,
        e: 1,
        b: 1
      },
      val: '默认'
    }
    new Vue({
    
    
      data: obj,
      el: '#app',
      template: `123{
     
     {a}}{
     
     {b}}{
     
     {val}}<input type="text" value='1'/>`
    })

猜你喜欢

转载自blog.csdn.net/qq_43505774/article/details/112876835