vue模板实现2-改进

2018-05-08  本文已影响0人  恒星的背影

这是一个改进版,这次只会处理元素内的文本,不会理会元素上的双括号。基本的原理就是递归遍历被vue绑定的根元素,将每个元素内的文本都处理一遍。

const handleStr = (str, data) => {               // 
  const reg = /{{\w+}}/g
  const arr = str.match(reg) || []

  arr.forEach((item)=>{
    const key = item.slice(2, -2)
    
    if(data[key] === undefined) {
      str = str.replace(item, '')
      console.error(`[vue warn] ${key} is undefined`)
    }
    else {
      str = str.replace(item, data[key])
    }
  })
  
  return str
}

const traverse = (node, data) => {                    // 遍历
  node.childNodes.forEach(item => {
    if(item.nodeName === '#text'){
      item.textContent = handleStr(item.textContent, data)
    }
    else {
      traverse(item, data)
    }
  });
}

class Vue {
  constructor(obj) {
    const {el, data} = obj
    const node = document.querySelector(el)

    traverse(node, data)
  }
}
上一篇 下一篇

猜你喜欢

热点阅读