从零开始实现vue
实现 Vue 的核心功能
Vue 的核心功能包括响应式数据绑定、虚拟 DOM 和模板编译。以下是从零开始实现 Vue 核心功能的关键步骤。
响应式数据系统
通过 Object.defineProperty 或 Proxy 实现数据劫持,监听数据变化并触发更新。
function defineReactive(obj, key, val) {
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
dep.depend()
return val
},
set(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}
依赖收集系统
实现一个简单的依赖收集系统,管理所有依赖关系。
class Dep {
constructor() {
this.subscribers = new Set()
}
depend() {
if (activeUpdate) {
this.subscribers.add(activeUpdate)
}
}
notify() {
this.subscribers.forEach(sub => sub())
}
}
虚拟 DOM 实现
创建一个简单的虚拟 DOM 结构,并实现 diff 算法。
function createElement(tag, props, children) {
return { tag, props, children }
}
function render(vnode) {
if (typeof vnode === 'string') {
return document.createTextNode(vnode)
}
const el = document.createElement(vnode.tag)
for (const key in vnode.props) {
el.setAttribute(key, vnode.props[key])
}
vnode.children.forEach(child => {
el.appendChild(render(child))
})
return el
}
模板编译
实现简单的模板编译,将模板字符串转换为渲染函数。
function compile(template) {
const ast = parse(template)
const code = generate(ast)
return new Function(`with(this){return ${code}}`)
}
function parse(template) {
// 简化版解析器
return {
type: 'element',
tag: 'div',
children: [
{ type: 'text', content: 'Hello World' }
]
}
}
function generate(ast) {
// 简化版代码生成
return `createElement('div', {}, ['Hello World'])`
}
组件系统
实现基础的组件系统,支持组件注册和渲染。
class Vue {
constructor(options) {
this.$options = options
this._data = options.data()
this._proxyData()
this.$el = document.querySelector(options.el)
this.compile()
}
_proxyData() {
Object.keys(this._data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return this._data[key]
},
set(val) {
this._data[key] = val
}
})
})
}
compile() {
const renderFn = compile(this.$options.template)
this.update = () => {
const vnode = renderFn.call(this)
const newEl = render(vnode)
this.$el.parentNode.replaceChild(newEl, this.$el)
this.$el = newEl
}
this.update()
}
}
使用方法
创建一个简单的 Vue 实例。
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello Vue!'
}
},
template: '<div>{{ message }}</div>'
})
优化方向
实现更完整的 Vue 功能需要考虑更多细节,如计算属性、指令系统、生命周期钩子、组件通信等。上述代码提供了最基础的核心功能实现思路。







