html
<div id="app">
<input type="text" v-model="school.name">
<div>{
{school.name}}</div>
<div>{
{school.age}}</div>
<!-- 如果数据不变化 视图就不会刷新 -->
{
{getNewname}}
<!-- 我们在内部 会匹配 {
{}} -->
<button v-on:click='handle'>更新操作</button>
</div>
js
let vm = new Vue({
el: '#app',
data: {
handle: {
name: "曹曹",
age: 10
}
},
computed: {
getNewname() {
return this.handle.name + '构架'
}
},
methods: {
handle() {
this.handle.name = "曹操"
}
},
})
//观察者 (发布订阅) 观察者 被观察者
class Dep {
constructor() {
this.subs = [];
}
//订阅
addSub(watcher) { //添加watcher
this.subs.push(watcher);
}
//发布
notify() {
this.subs.forEach(watcher => watcher.update());
}
}
class Watcher {
constructor(vm, expr, cb) {
this.vm = vm;
this.expr = expr;
this.cb = cb;
//默认存放一个老值
this.oldValue = this.get();
}
get() {
Dep.target = this;//先把自己放到this上
//取值 把这个观察者 和数据关联起来
let value = CompileUtil.getVal(this.vm, this.expr);
Dep.target = null; //不取消 任何值取值 都会添加watcher
return value;
}
update() {//数据变化后 会调用观察者的update方法
let newVal = CompileUtil.getVal(this.vm, this.expr);
if (newVal !== this.oldValue) {
this.cb(newVal);
}
}
}
// vm.$watch(vm,'school.name',(newVal)=>{ 观察者就像这个值一变就会出发事件