vue2响应式简易版)
Posted 嘴巴嘟嘟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue2响应式简易版)相关的知识,希望对你有一定的参考价值。
响应式做法:发布订阅模式+数据绑定
<!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>
<script type="module">
import Observer from './index.js'
let obj = new Observer(
name: "小明",
age: 18,
demo:
name: "小小明"
)
obj.value.age = 15
obj.value.demo.name = '大明'
console.log(obj.value)
</script>
</body>
</html>
export class Observer
constructor(value)
this.value = value
if (Array.isArray(value))
// 数组
else
// 对象
this.walk(value)
walk (obj)
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++)
defineReactive(obj, keys[i])
function defineReactive (obj, key, val)
if (arguments.length === 2)
val = obj[key]
if (typeof val === 'object')
console.log('递归')
new Observer(val)
Object.defineProperty(obj, key,
enumerable: true,
configurable: true,
get ()
console.log(`$key属性被读取`)
return val
,
set (newVal)
console.log(`$key属性被修改`)
val = newVal
)
以上是关于vue2响应式简易版)的主要内容,如果未能解决你的问题,请参考以下文章