声明
最近在学习Vue源码,学习之余,参考大神的self-vue,也就是 这篇文章。在学习过程中一边加上了注释,增强了可读性。现在把他分享给正在学习路上的你,愿你能少走些弯路。
我在源码的基础上删改了部分代码,并且使用es6语法。
目录结构
────────────────────────────────────────
├── index.html 入口页面 ││
├── js ││
│ ├── index.js 主体 ││
│ ├── compile.js 编译及创建虚拟DOM ││
│ ├── watcher.js 数据劫持事件调度中心 ││
│ ├── observer.js 响应式,Dep队列 ││
────────────────────────────────────────
源码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>self-vue</title>
</head>
<style>
#app {
text-align: center;
}
</style>
<body>
<div id="app">{
{
name}}
<h2>{
{
title}}</h2>
<input v-model="name">
<h1>{
{
name}}</h1>
<h3 id="hei">{
{
height}}</h3>
<button v-on:click="clickMe">{
{
title}}</button>
</div>
</body>
<script src="js/observer.js"></script>
<script src="js/watcher.js"></script>
<script src="js/compile.js"></script>
<script src="js/index.js"></script>
<script type="text/javascript">
let myvue = new SelfVue({
el: '#app',
data: {
title: 0,
name: 'canfoo',
height:'18cm',
ondblclickMe:'sss'
},
methods: {
clickMe () {
this.title ++
}
},
mounted: function () {
setTimeout(()=>{
alert('挂载完毕')
})
}
});
</script>
</html>
index.js
function SelfVue (options) {
const self = this; //缓存vm实例this
self.data = options.data;
self.methods = options.methods;
Object.keys(this.data).forEach(function(key) {
//代理
self.proxyKeys(key); //调用原型链上的proxyKeys方法
});
observe(this.data); //调用observe,将data传入
new Compile(options.el, this); //生成Compile实例
options.mounted.call(this