vue模板实现2-改进

这是一个改进版,这次只会处理元素内的文本,不会理会元素上的双括号。基本的原理就是递归遍历被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)
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容