javascript --- > vue中简单的模板渲染

一层的渲染

将下面的模板中的mustache语法使用给定数据渲染.
模板如下

<div id="root">
  <div>
    <div>
      <p>{{name}} - {{message}}</p>
    </div>
  </div>
  <p>{{name}}</p>
  <p>{{msg}}</p>
</div>

数据如下

const data = {
	name: '一个新name',
	message: '一个消息',
	msg: '哈哈哈'
}

思路

  • 首先使用document.querySelector方法获取DOM结构
  • 然后得到其所有的子元素,通过节点类型(node.nodeType)来判断其是文本节点还是元素节点
  • 如果是文本节点,则使用正则表达式来判断,文本值中是否有mustache语法.
  • 如果有则用data中的数据去替换它

知识点

  • 使用正则表达式来判断是否含有{{}}, 若有解析出其中的值.使用data中的值替换
const mustache = /\{\{(.+?)\}\}/g;  // 这个正则规则匹配`{{}}`,其中(.+?)代表任意的字符
// 获取文本节点的值, 假设是 `<p>{{ name }}</p>`
let txt = textNode.nodeValue
txt = txt.replace(mustache, function(_, g){
	return data[g.trim()]   // data = {name: '一个新name'}
})

实现

const mustache = /\{\{(.+?)\}\}/g;
let tmpNode = document.quertSelector('#root')
let data = {
	name: '一个新name',
	message: '一个消息',
	msg: '哈哈哈'
}
function compiler(template, data) {
	let childNodes = template.childNodes
	for(let i = 0 , len = childNodes.length; i < len ; i++){
		let nodeType = childNodes[i].nodeType
		if(type == 3 ){
			// 文本节点
			let txt = childNodes[i].nodeValue;
			// 得到替换后的文本
			txt = txt.replace(mustache, function(_, g){
				return data[g.trim()]
			})
			// 将替换后的文本放到DOM中
			childNodes[i].nodeValue = txt
		} else if(type == 1) {
			compiler(childNodes[i], data)
		}
	}
}

深层次的渲染

  • 上面的函数只能替换简单对象,而不能替换引用类型的对象
  • 即: a.name之类的就无法替换
  • 需要使用对象深层次遍历的方法
  • 根据路径得到对象中的值
function getValueByPath(obj, path){
	let res = obj,currProp,props = path.split('.')
	while((currProp = props.shift())){
		if(!res[currProp]){
			return undefined
		} else {
			res = res[currProp]
		}
	}
	return res
}
function compiler(template, data){
	// 其他位置和上述一样
	// 仅改写文本节点中的
	...
	if(type == 3){
		// 文本节点
		let txt = childNodes[i].nodeValue
		// 得到替换后的文本
		txt = txt.replace(mustache, function(_, g){
			return getValueByPath(data, g.trim())
		})
		childNodes[i].nodeValue = txt
	}
	...
}
发布了228 篇原创文章 · 获赞 41 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/104563716
今日推荐