1.手写vue 之 了解数据响应式原理并手写代码
发布于 2022年 04月 30日 13:55
理解vue的设计思想
将视图View的状态和行为抽象化,让我们将视图 UI 和业务逻辑分开。
MVVM框架的三要素:数据响应式、模板引擎及其渲染
- 数据响应式:监听数据变化并且在视图中更新
- Object.definePropetry()
- Proxy
- 模板引擎: 提供描述视图的模板语法
插值:{{}} 指令: v-bind,v-on,v-model,v-for,v-if
- 渲染:如何将模板转换为html
模板=>vdom =>dom
//传入对象obj,给他定义一个属性key,初始值为val
// 该属性未来的访问会被拦截,这样就实现了响应式
function defineReactive(obj,key,val){
//向下递归遍历
observe(val) //由于在获取(设置)对象的孙子辈的元素 时不能实现响应做的处理obj.a.b
Object.defineProperty(obj,key,val,{
get(){
console.log("get",key)
return val;
},
set()(newVal){
if(newVal !== val){
console.log("set", key);
observe(newVal)
val = newVal;
}
}
}
}
// 自动设置一个对象的所有属性为响应式的
function observe(obj){
if(type obj !== "Object" || obj == null){
return obj;
}
Object.keys(obj).forEach((key) =>{
defineReactive(obj, key, obj[key]);
})
}
const obj = {
foo: "foo",
bar: "bar",
baz: { a: 1 },
arr: [1,2,3]
};
// defineReactive(obj, 'foo', 'foo')
observe(obj);
应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script>
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log('get', key);
return val
},
set(newVal) {
if (newVal !== val) {
console.log('set', key);
val = newVal
update()
}
}
})
}
const obj = {}
defineReactive(obj, 'foo', '')
function update() {
app.innerText = obj.foo
}
setInterval(() => {
obj.foo = new Date().toLocaleTimeString()
}, 1000)
</script>
</body>
</html>