首頁  >  文章  >  web前端  >  如何實作vue2.0響應式(詳細教學)

如何實作vue2.0響應式(詳細教學)

亚连
亚连原創
2018-06-05 17:48:441696瀏覽

這篇文章主要介紹了淺談實現vue2.0響應式的基本思路,現在分享給大家,也給大家做個參考。

最近看了vue2.0源碼關於響應式的實現,以下博文將透過簡單的程式碼還原vue2.0關於響應式的實現思路。

注意,這裡只是實現思路的還原,對於裡面各種細節的實現,比如說數組裡面資料的操作的監聽,以及物件嵌套這些細節本實例都不會涉及到,如果想了解更細節的實現,可以透過閱讀原始碼observer資料夾以及instance資料夾裡面的state檔案具體了解。

首先,我們先定義好實作vue物件的結構

class Vue {
  constructor(options) {
    this.$options = options;
    this._data = options.data;
    this.$el = document.querySelector(options.el);
  }
}

第一步:將data下面的屬性變成observable

使用Object .defineProperty對資料物件做屬性get和set的監聽,當有資料讀取和賦值運算時則呼叫節點的指令,這樣使用最通用的=等號賦值就可以觸發了。

//数据劫持,监控数据变化
function observer(value, cb){
 Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
}

function defineReactive(obj, key, val, cb) {
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: ()=>{
   return val
  },
  set: newVal => {
   if(newVal === val)
    return
   val = newVal
  }
 })
}

第二步:實作一個訊息訂閱器​​

很簡單,我們維護一個數組,這個數組,就放訂閱者,一旦觸發notify,訂閱者就呼叫自己的update方法

class Dep {
 constructor() {
  this.subs = []
 }
 add(watcher) {
  this.subs.push(watcher)
 }
 notify() {
  this.subs.forEach((watcher) => watcher.cb())
 }
}

每次set函數,呼叫的時候,我們觸發notify,實作更新

那麼問題來了。誰是訂閱者。對,是Watcher。 。一旦dep.notify()就遍歷訂閱者,也就是Watcher,並且呼叫他的update()方法

function defineReactive(obj, key, val, cb) {
 const dep = new Dep()
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: ()=>{
   return val
  },
  set: newVal => {
   if(newVal === val)
    return
   val = newVal
   dep.notify()
  }
 })
}

第三步:實作一個Watcher

##Watcher的實作比較簡單,其實就是執行資料變更時我們要執行的操作

class Watcher {
 constructor(vm, cb) {
  this.cb = cb
  this.vm = vm
 }
 update(){
  this.run()
 }
 run(){
  this.cb.call(this.vm)
 } 
}

第四步:touch拿到依賴

上述三步,我們實作了資料改變可以觸發更新,現在問題是我們無法將watcher與我們的資料連結在一起。

我們知道data上的屬性設定defineReactive後,修改data 上的值會觸發 set。那我們取data上值就是會觸發 get了。所以可以利用這一點,先執行以下render函數,就可以知道視圖的更新需要哪些資料的支持,並且把它記錄為資料的訂閱者。

function defineReactive(obj, key, val, cb) {
 const dep = new Dep()
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: ()=>{
   if(Dep.target){
    dep.add(Dep.target)
   }
   return val
  },
  set: newVal => {
   if(newVal === val)
    return
   val = newVal
   dep.notify()
  }
 })
}

最後我們來看用一個代理實作將我們對data的資料存取綁定在vue物件上

 _proxy(key) {
  const 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
   }
  })
}

Object.keys(options.data).forEach(key => this._proxy(key))

下面就是整個實例的完整程式碼

class Vue {
 constructor(options) {
  this.$options = options;
  this._data = options.data;
  this.$el =document.querySelector(options.el);
  Object.keys(options.data).forEach(key => this._proxy(key))
  observer(options.data)
  watch(this, this._render.bind(this), this._update.bind(this))
 }
 _proxy(key) {
  const 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
   }
  })
 }
 _update() {
  console.log("我需要更新");
  this._render.call(this)
 }
 _render() {
  this._bindText();
 }

 _bindText() {
  let textDOMs=this.$el.querySelectorAll('[v-text]'),
  bindText;
  for(let i=0;i defineReactive(value, key, value[key] , cb))
}

function defineReactive(obj, key, val, cb) {
 const dep = new Dep()
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: ()=>{
   if(Dep.target){
    dep.add(Dep.target)
   }
   return val
  },
  set: newVal => {
   if(newVal === val)
    return
   val = newVal
   dep.notify()
  }
 })
}
function watch(vm, exp, cb){
 Dep.target = new Watcher(vm,cb);
 return exp()
}

 class Watcher {
 constructor(vm, cb) {
  this.cb = cb
  this.vm = vm
 }
 update(){
  this.run()
 }
 run(){
  this.cb.call(this.vm)
 } 
}

class Dep {
 constructor() {
  this.subs = []
 }
 add(watcher) {
  this.subs.push(watcher)
 }
 notify() {
  this.subs.forEach((watcher) => watcher.cb())
 }
}
Dep.target = null; 
var demo = new Vue({
 el: '#demo',
 data: {
 text: "hello world"
 }
 })
 
setTimeout(function(){
 demo.text = "hello new world"
 
}, 1000)

 
  

上面就是整個vue資料驅動部分的整個思路。如果想深入了解更細節的實現,建議深入去看vue這部分的程式碼。

上面是我整理給大家的,希望今後對大家有幫助。

相關文章:

使用vue element-ui ajax這幾樣技術,實作一個表格的實例

##利用live-server如何建立本機伺服器和自動刷新,具體方法有哪些?

解決低版本的瀏覽器不支援es6的import問題

#

以上是如何實作vue2.0響應式(詳細教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn