<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="title">
原有标题
</div>
<button id="btn">button </button>
<script>
var data ={
title:"practice",
name:"cuiyang"
}
observer(data)
function observer(obj){
Object.keys(obj).forEach((item)=>{
defineReactive(obj,item,obj[item])
})
}
function defineReactive(obj,key,value){
Object.defineProperty(obj,key,{
get(){
return value
},
set(newValue){
value=newValue
title.innerHTML=value
}
})
}
console.log(data)
var title=document.getElementById('title');
var btn=document.getElementById('btn');
btn.onclick=function(){
data.title="改变标题"
}
</script>
</body>
</html>
vue.js源码