总结:
将
Observer
提取到common.js
中利用正则、
bind
、eval
替换模板的值缺点:
- 模板正则匹配,没有做校验
代码:
<!DOCTYPE html>
<html>
<head>
<title>dymanic_data_binding_03</title>
<meta charset="utf-8">
<style type="text/css">
</style>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/default.min.css" />
</head>
<body>
<ol>要求:
<li>
<h3>请实现如下的这样一个 Vue,传入参数是一个 Selector 和一个数据对象,程序需要将 HTML 模板片段渲染成正确的模样。 这就是一次性的静态数据绑定。</h3>
<pre><code class="html">
<!--页面中原本的html模板片段-->
<div id = "app">
<p>姓名: {{user.name}}</p>
<p>年龄:{{user.age}}</p>
</div>
<!-- 最终在页面中渲染出来的结果 -->
<div id="app"><p>姓名:youngwind</p><p> 年龄:25 </p></div>
</code></pre>
<pre><code>
let app = new Vue({
el: '#app',
data: {
user: {
name: 'youngwind',
age: 25
}
}
});
</code></pre>
</li>
</ol>
<div id = "app">
<p>姓名: {{user.name}}</p>
<p>年龄:{{user.age}}</p>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script src="/assets/js/common.js"></script>
<script type="text/javascript">
function Vue (options) {
if (_getType(options) !== 'object') throw 'options should be an object';
this.el = options.el || '';
this.vm = new Observer(options.data || {});
this.data = this.vm.data;
this.watchEvents = this.vm.watchEvents;
this.el && this.parseTemplate();
}
Vue.prototype = Observer.prototype;
Vue.prototype.parseTemplate = function () {
let _this = this,
$el = this.$el = document.querySelector(this.el),
curHTML = $el.innerHTML,
braceRreg = /{{(.*)}}/g;
_getDataVal = _getExecuteVal.bind(this.data);
$el.innerHTML = curHTML.replace(braceRreg, (match, p1, offset) => {
return _getDataVal(p1) || match;
});
};
</script>
</body>
</html>