自己实现vue
实现简易 Vue.js 的核心功能
数据响应式系统
使用 Object.defineProperty 或 Proxy 实现数据劫持。当数据变化时自动更新视图。
function observe(data) {
if (!data || typeof data !== 'object') return
Object.keys(data).forEach(key => {
defineReactive(data, key, data[key])
})
}
function defineReactive(obj, key, val) {
observe(val)
const dep = new Dep()
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
Dep.target && dep.addSub(Dep.target)
return val
},
set(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}
依赖收集系统
实现发布-订阅模式,管理所有观察者(Watcher)。

class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
Dep.target = null
模板编译
将模板转换为渲染函数,解析指令和插值表达式。
class Compiler {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
if (this.$el) {
this.compile(this.$el)
}
}
compile(node) {
const childNodes = node.childNodes
Array.from(childNodes).forEach(child => {
if (this.isElement(child)) {
this.compileElement(child)
} else if (this.isInterpolation(child)) {
this.compileText(child)
}
if (child.childNodes && child.childNodes.length > 0) {
this.compile(child)
}
})
}
// 其他辅助方法...
}
虚拟DOM和Diff算法
实现高效的DOM更新策略。

function patch(oldVnode, vnode) {
if (!oldVnode) {
createElm(vnode)
} else if (sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode)
} else {
const parent = oldVnode.parentNode
createElm(vnode, parent, oldVnode.nextSibling)
removeVnodes(parent, [oldVnode], 0, 0)
}
return vnode.elm
}
组件系统
实现组件化架构,支持props、events、slots等特性。
Vue.component = function(name, componentOptions) {
this.options.components[name] = componentOptions
}
function createComponent(Ctor, data, context, children) {
const propsData = extractProps(data, Ctor.options.props)
const vnode = new VNode(
`vue-component-${Ctor.cid}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners: data.on, children }
)
return vnode
}
生命周期管理
实现创建、挂载、更新、销毁等生命周期钩子。
function callHook(vm, hook) {
const handlers = vm.$options[hook]
if (handlers) {
handlers.forEach(handler => handler.call(vm))
}
}
实现要点
- 响应式系统是核心,需要正确处理嵌套对象和数组
- 虚拟DOM实现需要考虑组件树的结构
- 模板编译需要处理各种指令(v-if, v-for等)
- 组件系统需要处理父子组件通信
- 需要实现nextTick机制保证更新顺序
进阶优化方向
- 使用Proxy替代Object.defineProperty
- 实现服务端渲染(SSR)支持
- 添加TypeScript类型支持
- 优化Diff算法性能
- 实现自定义渲染器(如Weex、小程序支持)
以上代码展示了Vue核心功能的简化实现,实际完整实现需要考虑更多边界条件和性能优化。






