<body>
<h3 v-html="msg"></h3>
<input type="text" v-model="msg">
<script>
// 初始化数据 -- vue优化,扁平化数据
let data = {
msg: 'hello',
user: { id: 100 }
}
// 劫持或代理
observer(data)
// 编译模板
compileTmeplate(data)
function compileTmeplate(target) {
/* document.querySelectorAll('[v-model]').forEach(node => {
console.log(node)
}) */
document.querySelectorAll('*').forEach(node => {
[...node.attributes].forEach(attr => {
if (/^v-/.test(attr.name)) { // 双向绑定所要用到的属性
if (attr.name === 'v-model') {
node.value = target[attr.nodeValue]
// 表单项,事件和数据绑定
node.addEventListener('input', function () {
// 更新数据
target[attr.nodeValue] = this.value.trim()
})
} else {
node.innerHTML = target[attr.nodeValue]
}
}
})
})
}
function observer(target) {
if (Object.prototype.toString.call(target) != '[object Object]') return;
for (let key in target) {
defineReactive(target, key, target[key])
}
}
// 代理
function defineReactive(target, key, value) {
observer(value)
Object.defineProperty(target, key, {
get() {
console.log('get')
return value
},
set(val) {
console.log('set')
if (val != value) {
document.querySelectorAll('[v-html]').forEach(node => {
node.innerHTML = val
})
document.querySelectorAll('[v-model]').forEach(node => {
node.value = val
})
value = val
}
}
})
}
</script>
</body>
实现简约版本的 vue
最新推荐文章于 2024-08-25 09:57:22 发布