创建一个vm的类,来写一个简易的MVVM模型
// index.html
<html>
<body>
<div id="app">
<p>{{name}}</p>
<p v-text="age"></p>
<div v-html="html"></div>
</div>
<script src="./vm.js"></script>
<script>
new VM({
el: "#app", // el只传递选择器
data: {
name: "I am test",
age: "17",
html: "<button>这是一个按钮</button>"
}
})
</script>
</body>
</html>
定义mv类
// vm.js
class VM {
constructor(options) {
// 数据劫持,做响应式
this.$data = options.data;
this.$el = options.el;
this.observe(this.$data);
new Compiler(this, this.$el);
}
}
// 只做对象的响应式
observe(data) {
if(!data || typeof data !== 'object') {
return;
}
Object.keys(data).forEach(k => {
this.defineReactive(data, k, data[k]);
this.proxy(k)
})
}
// 做数据代理
proxy(key) {
Object.defineProperty(this, key {
get() {
return this.$data[key]
},
set(value) {
this.$data[key] = value
}
})
}
// 使用Object.defineProperty方法做数据拦截
defineReactive(obj, key, value) {
this.observe(value);
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
if(Dep.target !== null) {
dep.addDep(Dep.target)
}
return value
},
set(val) {
if(val === value) {
return;
}
value = val
dep.notify()
}
})
}
// 定义Dep类
class Dep {
constructor() {
this.deps = [];
}
// dep其实是Watcher的一个实例
addDep(dep) {
this.deps.push(dep)
}
// 执行依赖的update方法
notify() {
this.deps.forEach(dep => dep.update())
}
}
// 定义Watch类
class Watcher {
constructor(vm, key, cb) {
this.$vm = vm;
this.$key = key;
this.$cb = cb;
Dep.target = this;
this.$vm[this.$key];
Dep.target = null;
}
update() {
this.$cb && this.$cb(this.$vm[this.$key])
}
}
在初始化VM时,会对DOM进行编译
class Compiler {
constructor(vm, el) {
this.$vm = vm;
if(!el) {
return;
}
const rootDom = document.querySelector(el);
const fragment = this.node2fragment(rootDom);
this.compile(fragment);
rootDom.appendChild(fragment)
}
// 将dom放入frament中
node2fragment(dom) {
let child = null;
const fragment = document.createDocumentFragment();
while(child = dom.firstChild) {
fragment.appendChild(child);
}
return fragment;
}
// 编译dom
compile(fragment) {
const childNodes = fragment.childNodes;
Array.property.forEach.call(childNodes, node => {
if(this.isElement(node)) { // 判断是否为元素
} else if (this.isInterpolation(node)) { // 判断是否为插值
this.compileInterpolation(this.$vm, node)
}
})
}
// 判断是否为元素
isElement(node) {
return node.nodeType === 1
}
// 判断是否为插值
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
}
// 编译插值
compileInterpolation(vm, node) {
this.update(node, RegExp.$1, 'text');
}
// 更新函数
update(vm, node, key, dir) {
const updateFn = this[`dir`Updater];
updateFn && updateFn(node, vm[key]);
// 更新函数中,创建依赖收集
new Watcher(vm, key, (val) => {
updateFn && updateFn(node, val)
})
}
// 文本更新方法
textUpdater(node, value) {
node.textContent = value;
}
}
确实指令,以及事件的编译,有时间在补充