js实现v
以下是JavaScript实现Vue.js核心功能的简化示例,涵盖数据绑定、指令和虚拟DOM的基本概念:

数据绑定
通过Object.defineProperty实现响应式数据:

class Observer {
constructor(data) {
this.observe(data)
}
observe(data) {
if (!data || typeof data !== 'object') return
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
defineReactive(obj, key, val) {
const dep = new Dep()
this.observe(val)
Object.defineProperty(obj, key, {
get() {
Dep.target && dep.addSub(Dep.target)
return val
},
set(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}
}
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
指令解析
实现v-model双向绑定:
class Compiler {
constructor(el, vm) {
this.vm = vm
this.el = document.querySelector(el)
this.compile(this.el)
}
compile(node) {
Array.from(node.childNodes).forEach(child => {
if (this.isElementNode(child)) {
this.compileElement(child)
} else if (this.isTextNode(child)) {
this.compileText(child)
}
if (child.childNodes && child.childNodes.length) {
this.compile(child)
}
})
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (this.isDirective(attr.name)) {
const dir = attr.name.substring(2)
this[dir] && this[dir](node, attr.value)
}
})
}
model(node, exp) {
node.value = this.vm[exp]
new Watcher(this.vm, exp, val => {
node.value = val
})
node.addEventListener('input', e => {
this.vm[exp] = e.target.value
})
}
}
虚拟DOM简化实现
class VNode {
constructor(tag, data, children, text) {
this.tag = tag
this.data = data
this.children = children
this.text = text
}
}
function createElement(tag, data, children) {
return new VNode(tag, data, children)
}
function patch(oldVnode, vnode) {
if (!oldVnode) {
return createElm(vnode)
}
const isRealElement = oldVnode.nodeType !== undefined
if (isRealElement) {
const parent = oldVnode.parentNode
const elm = createElm(vnode)
parent.insertBefore(elm, oldVnode)
parent.removeChild(oldVnode)
return elm
}
}
function createElm(vnode) {
if (vnode.tag) {
vnode.elm = document.createElement(vnode.tag)
if (vnode.children) {
vnode.children.forEach(child => {
vnode.elm.appendChild(createElm(child))
})
}
} else {
vnode.elm = document.createTextNode(vnode.text)
}
return vnode.elm
}
完整流程整合
class Vue {
constructor(options) {
this.$options = options
this._data = options.data
new Observer(this._data)
Object.keys(this._data).forEach(key => {
this.proxyData(key)
})
new Compiler(options.el, this)
}
proxyData(key) {
Object.defineProperty(this, key, {
get() {
return this._data[key]
},
set(newVal) {
this._data[key] = newVal
}
})
}
}
以上代码实现了:
- 数据劫持和响应式系统
- 模板编译和指令解析
- 虚拟DOM的简化版本
- 观察者模式实现依赖收集
使用时通过new Vue({el: '#app', data: {...}})初始化,类似Vue的API设计。实际Vue源码还包含组件系统、生命周期管理等更复杂机制。






