美文网首页
vue模板实现2-改进

vue模板实现2-改进

作者: 恒星的背影 | 来源:发表于2018-05-08 21:30 被阅读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)
  }
}

相关文章

网友评论

      本文标题:vue模板实现2-改进

      本文链接:https://www.haomeiwen.com/subject/vdfgrftx.html