這一次 徹底理解Vue的watch實現原理及其實現方式(轉)


畫一張watch的簡單工作流程圖:

把上文的 Dep,Oberver,Wather拿過來並做部分更改(增加收集依賴去重處理):

Dep代碼如下:

//標識當前的Dep id
let uidep = 0
class Dep{
    constructor () {
        this.id = uidep++
        // 存放所有的監聽watcher
        this.subs = []
      }
 
      //添加一個觀察者對象
      addSub (Watcher) {
        this.subs.push(Watcher)
      }
 
      //依賴收集
    depend () {
        //Dep.target 作用只有需要的才會收集依賴
        if (Dep.target) {
          Dep.target.addDep(this)
        }
    }
 
    // 調用依賴收集的Watcher更新
    notify () {
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
          subs[i].update()
        }
      }
}
 
Dep.target = null
const targetStack = []
 
// 為Dep.target 賦值

function pushTarget (Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = Watcher
}
function popTarget () {
Dep.target = targetStack.pop()
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM