const v = new Vue({
data:{
a:1,
b:2
}
})
v.$watch("a",()=>console.log("哈哈,$watch成功"))
setTimeout(()=>{
v.a = 5
},2000) //打印 哈哈,$watch成功
export default class Observer{
constructor(value) {
this.value = value
this.walk(value)
}
//递归。。让每个字属性可以observe
walk(value){
Object.keys(value).forEach(key=>this.convert(key,value[key]))
}
convert(key, val){
defineReactive(this.value, key, val)
}
}
export function defineReactive (obj, key, val) {
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>val,
set:newVal=> {
childOb = observe(newVal)//如果新赋值的值是个复杂类型。再递归它,加上set/get。。
}
})
}
export function observe (value, vm) {
if (!value || typeof value !== 'object') {
return
}
return new Observer(value)
}
export default class Dep {
constructor() {
this.subs = []
}
addSub(sub){
this.subs.push(sub)
}
notify(){
this.subs.forEach(sub=>sub.update())
}
}
export function defineReactive (obj, key, val) {
var dep = new Dep()
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>val,
set:newVal=> {
var value = val
if (newVal === value) {
return
}
val = newVal
childOb = observe(newVal)
dep.notify()
}
})
}
export default class Watcher {
constructor(vm, expOrFn, cb) {
this.cb = cb
this.vm = vm
//此处简化.要区分fuction还是expression,只考虑最简单的expression
this.expOrFn = expOrFn
this.value = this.get()
}
update(){
this.run()
}
run(){
const value = this.get()
if(value !==this.value){
this.value = value
this.cb.call(this.vm)
}
}
get(){
//此处简化。。要区分fuction还是expression
const value = this.vm._data[this.expOrFn]
return value
}
}
export default class Watcher {
....省略未改动代码....
get(){
Dep.target = this
//此处简化。。要区分fuction还是expression
const value = this.vm._data[this.expOrFn]
Dep.target = null
return value
}
}
export function defineReactive (obj, key, val) {
var dep = new Dep()
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
// 说明这是watch 引起的
if(Dep.target){
dep.addSub(Dep.target)
}
return val
},
set:newVal=> {
var value = val
if (newVal === value) {
return
}
val = newVal
childOb = observe(newVal)
dep.notify()
}
})
}
import Watcher from '../watcher'
import {observe} from "../observer"
export default class Vue {
constructor (options={}) {
//这里简化了。。其实要merge
this.$options=options
//这里简化了。。其实要区分的
let data = this._data=this.$options.data
Object.keys(data).forEach(key=>this._proxy(key))
observe(data,this)
}
$watch(expOrFn, cb, options){
new Watcher(this, expOrFn, cb)
}
_proxy(key) {
var self = this
Object.defineProperty(self, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return self._data[key]
},
set: function proxySetter (val) {
self._data[key] = val
}
})
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有