html的底层原理,vue底层原理实现.html

本文通过一个简单的 Vue.js 示例介绍了 Vue 中响应式数据更新的实现原理。具体包括数据劫持、依赖收集及更新机制等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Document

{{message}}

class Vue {

constructor(options) {

this.$el = options.el

this.$data = options.data

this.$options = options

new Observer(this.$data)

Object.keys(this.$data).forEach(key => {

this._proxy(key)

})

new Compiler(this.$el, this)

new Computed(this, this.$options);

}

_proxy(key) {

console.log(key);

Object.defineProperty(this, key, {

configurable: true,

enumerable: true,

get() {

return this.$data[key]

},

set(newValue) {

this.$data[key] = newValue

}

})

}

}

class Observer {

constructor(data) {

this.data = data

Object.keys(data).forEach(key => {

this._defineReactive(this.data, key, data[key])

})

}

_defineReactive(data, key, value) {

const dep = new Dep()

Object.defineProperty(data, key, {

configurable: true,

enumerable: true,

get() {

if (Dep.target) {

dep.addSub(Dep.target)

}

return value

},

set(newValue) {

if (newValue === value) {

return

}

value = newValue

dep.notify()

}

})

}

}

class Dep {

constructor() {

this.subs = []

}

addSub(sub) {

this.subs.push(sub)

}

notify() {

this.subs.forEach(sub => {

sub.update()

})

}

}

const mustache = /\{\{(.+)\}\}/

class Compiler {

constructor(el, vm) {

this.el = document.querySelector(el)

this.vm = vm

this.frag = this._createFragment()

this.el.appendChild(this.frag)

}

_createFragment() {

const frag = document.createDocumentFragment()

let child;

while (child = this.el.firstChild) {

this._compile(child)

frag.appendChild(child)

}

return frag

}

_compile(node) {

// console.log(node);

if (node.nodeType === 1) {

const attrs = node.attributes

if (attrs.hasOwnProperty('v-model')) {

const nodeName = attrs['v-model'].nodeValue

node.addEventListener('input', e => {

this.vm[nodeName] = e.target.value

})

}

}

if (node.nodeType === 3) {

if (mustache.test(node.nodeValue)) {

const nodeName = RegExp.$1.trim()

console.log(nodeName);

new Watcher(node, nodeName, this.vm)

}

}

}

}

class Watcher {

constructor(node, key, vm) {

this.node = node

this.key = key

this.vm = vm

Dep.target = this;

this.update()

Dep.target = null

}

update() {

// console.log(this.vm.$data[this.key]);

this.node.nodeValue = this.vm[this.key]

}

}

class Computed {

constructor(vm, options) {

this.vm = vm

this.computed = this.options.computed

Object.keys(computed).forEach(function (key) {

Object.defineProperty(vm, key, {

get: typeof computed[key] === "function" ? computed[key] : computed[key].get,

set() { }

})

})

};

}

const app = new Vue({

el: '#app',

data: {

message: '哈哈哈'

}

})

一键复制

编辑

Web IDE

原始数据

按行查看

历史

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值