欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue發(fā)布訂閱模式實(shí)現(xiàn)過程圖解

 更新時(shí)間:2020年04月30日 09:59:46   作者:林中有風(fēng)  
這篇文章主要介紹了Vue發(fā)布訂閱模式實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

vue項(xiàng)目中不同組件間通信一般使用vuex,通常情況下vuex和EventBus不應(yīng)該混用,不過某些場(chǎng)景下不同組件間只有消息的交互,這時(shí)使用EventBus消息通知的方式就更合適一些。

圖解

html

<body>
 <script src="./Dvue.js"></script>
 <script>
  const app = new DVue({
   data: {
    test: "I am test",
    foo: {
     bar: "bar"
    }
   }
  })

  app.$data.test = "hello world!"
  // app.$data.foo.bar = "hello!"
 </script>
</body>

Dvue.js

class DVue {
 constructor(options) {
  this.$options = options

  // 數(shù)據(jù)響應(yīng)化
  this.$data = options.data
  this.observe(this.$data)

  // 模擬一下watcher創(chuàng)建
  // 激活get 并將依賴添加到deps數(shù)組上
  new Watcher()
  this.$data.test
  new Watcher()
  this.$data.foo.bar
 }

 observe(value) {
  // 判斷value是否是對(duì)象  
  if (!value || typeof value !== 'object') {
   return
  }
  
  // 遍歷該對(duì)象
  Object.keys(value).forEach(key => {
   this.defineReactive(value, key, value[key])
  })
 }

 // 數(shù)據(jù)響應(yīng)化
 defineReactive(obj, key, val) {
  // 判斷val內(nèi)是否還可以繼續(xù)調(diào)用(是否還有對(duì)象)
  this.observe(val) // 遞歸解決數(shù)據(jù)嵌套

  // 初始化dep
  const dep = new Dep()

  Object.defineProperty(obj, key, {
   get() {
    // 讀取的時(shí)候 判斷Dep.target是否有,如果有則調(diào)用addDep方法將Dep.target添加到deps數(shù)組上
    Dep.target && dep.addDep(Dep.target)
    return val
   },
   set(newVal) {
    if (newVal === val) {
     return;
    }
    val = newVal
    // console.log(`${key}屬性更新了:${val}`)
    dep.notify() // 更新時(shí)候調(diào)用該方法
   }
  })
 }
}


// Dep: 用來管理Watcher
class Dep {
 constructor() {
  // 這里存放若干依賴(watcher) |一個(gè)watcher對(duì)應(yīng)一個(gè)屬性
  this.deps = [];
 }

 // 添加依賴
 addDep (dep) {
  this.deps.push(dep)
 }

 // 通知方法
 notify() {
  this.deps.forEach(dep => dep.update())
 }
}

// Watcher
class Watcher {
 constructor () {
  // 將當(dāng)前watcher實(shí)例指定到Dep靜態(tài)屬性target上
  Dep.target = this  // 當(dāng)前this就是Watcher對(duì)象
 }

 update() {
  console.log('屬性更新了')
 }
}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論