最近2018中文字幕在日韩欧美国产成人片_国产日韩精品一区二区在线_在线观看成年美女黄网色视频_国产精品一区三区五区_国产精彩刺激乱对白_看黄色黄大色黄片免费_人人超碰自拍cao_国产高清av在线_亚洲精品电影av_日韩美女尤物视频网站

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
淺析Vue響應(yīng)系統(tǒng)原理與搭建Vue2.x迷你版

Vue2.x響應(yīng)式原理怎么實(shí)現(xiàn)的?

Vue 最獨(dú)特的特性之一,是其非侵入性的響應(yīng)式系統(tǒng)。那么什么是響應(yīng)式原理?

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名申請(qǐng)、網(wǎng)絡(luò)空間、營(yíng)銷軟件、網(wǎng)站建設(shè)、城關(guān)網(wǎng)站維護(hù)、網(wǎng)站推廣。

數(shù)據(jù)模型僅僅是普通的JavaScript對(duì)象,而當(dāng)我們修改數(shù)據(jù)時(shí),視圖會(huì)進(jìn)行更新,避免了繁瑣的DOM操作,提高開(kāi)發(fā)效率。簡(jiǎn)言之,在改變數(shù)據(jù)的時(shí)候,視圖會(huì)跟著更新。

了解概念之后,那么它是怎么實(shí)現(xiàn)的呢?

其實(shí)是利用Object.defineProperty()中的getter 和setter方法和設(shè)計(jì)模式中的觀察者模式。

那么,我們先來(lái)看下Object.defineProperty()。MDN中它是這樣解釋它的:Object.defineProperty()方法會(huì)直接在一個(gè)對(duì)象上定義一個(gè)新屬性,或者修改一個(gè)對(duì)象的現(xiàn)有屬性,并返回此對(duì)象。

 
 
 
 
  1. let data = {
  2.  msg:'hello'
  3. };
  4. let vm = {};
  5. Object.defineProperty(vm, 'msg', {
  6.         enumerable: true, // 可枚舉(可遍歷)
  7.         configurable: true, // 可配置(可以使用delete 刪除,可以通過(guò)defineProperty重新定義)
  8.         // 當(dāng)獲取值的時(shí)候執(zhí)行
  9.         get() {
  10.             console.log('get', data.msg);
  11.             return data.msg
  12.         },
  13.         // 當(dāng)設(shè)置值的時(shí)候執(zhí)行
  14.         set(newVal) {
  15.             if (newVal === data.msg) {
  16.                 return
  17.             }
  18.             data.msg = newVal;
  19.             console.log('set', data.msg);
  20.         }
  21. })
  22. // 測(cè)試
  23. console.log(vm.msg);
  24. /* 
  25. > "get" "hello"
  26. > "hello"
  27. */
  28. vm.msg = 'world'; // > "set" "world"

簡(jiǎn)單介紹Object.defineProperty()之后,接著就是了解觀察者模式,看到它,你可能會(huì)想起發(fā)布-訂閱模式。其實(shí)它們的本質(zhì)是相同的,但是也存在一定的區(qū)別。

我們不妨先來(lái)看下發(fā)布-訂閱模式。

發(fā)布-訂閱者模式里面包含了三個(gè)模塊,發(fā)布者,訂閱者和統(tǒng)一調(diào)度中心。這里統(tǒng)一調(diào)度中心相當(dāng)于報(bào)刊辦事大廳。發(fā)布者相當(dāng)與某個(gè)雜志負(fù)責(zé)人,他來(lái)中心這注冊(cè)一個(gè)的雜志,而訂閱者相當(dāng)于用戶,我在中心訂閱了這分雜志。每當(dāng)發(fā)布者發(fā)布了一期雜志,辦事大廳就會(huì)通知訂閱者來(lái)拿新雜志。發(fā)布-訂閱者模式由統(tǒng)一調(diào)度中心調(diào)用,因此發(fā)布者和訂閱者不需要知道對(duì)方的存在。

下面,我們將通過(guò)一個(gè)實(shí)現(xiàn)Vue自定義事件的例子來(lái)更進(jìn)一步了解發(fā)布-訂閱模式。

 
 
 
 
  1. function EventEmitter(){
  2.     // 初始化統(tǒng)一調(diào)度中心
  3.     this.subs = Object.create(null); // {'click':[fn1,fn2]}
  4. }
  5. // 注冊(cè)事件
  6. EventEmitter.prototype.$on = function (eventType,handler){
  7.         console.log(this);
  8.         this.subs[eventType]= this.subs[eventType]||[];
  9.         this.subs[eventType].push(handler);
  10. }
  11. // 觸發(fā)事件
  12. EventEmitter.prototype.$emit = function (eventType,data){
  13.         if(this.subs[eventType]){
  14.                 this.subs[eventType].forEach(handler => {
  15.                     handler(data);
  16.                 });
  17.         }
  18. }
  19. // 測(cè)試
  20. const em = new EventEmitter();
  21. //訂閱者
  22. em.$on('click1',(data)=>{
  23.     console.log(data);
  24. })
  25. // 發(fā)布者
  26. em.$emit('click1','maomin') //maomin

這種自定義事件廣泛應(yīng)用于Vue同級(jí)組件傳值。

接下來(lái),我們來(lái)介紹觀察者模式。

觀察者模式是由目標(biāo)調(diào)度,比如當(dāng)事件觸發(fā)時(shí),目標(biāo)就會(huì)調(diào)用觀察者的方法,所以觀察者模式的訂閱者(觀察者)與發(fā)布者(目標(biāo))之間存在依賴。

 
 
 
 
  1. // 發(fā)布者(目標(biāo))
  2. function Dep(){
  3.     this.subs = [];
  4. }
  5. Dep.prototype.addSub = function (sub){
  6.     if(sub&&sub.update){
  7.             this.subs.push(sub);
  8.     }
  9. }
  10. Dep.prototype.notify = function (data){
  11.         this.subs.forEach(sub=>{
  12.             sub.update(data);
  13.         })
  14. }
  15. // 訂閱者(觀察者)
  16. function Watcher(){}
  17.     Watcher.prototype.update=function(data){
  18.     console.log(data);
  19. }
  20. // 測(cè)試
  21. let dep = new Dep();
  22. let watcher = new Watcher();
  23. // 收集依賴
  24. dep.addSub(watcher);
  25. // 發(fā)送通知
  26. dep.notify('1');
  27. dep.notify('2');

下圖是區(qū)分兩種模式。

實(shí)現(xiàn)Vue2.x迷你版本

為什么要實(shí)現(xiàn)一個(gè)Vue迷你版本,目的就是加深對(duì)Vue響應(yīng)式原理以及其中一些API的理解。首先我們先來(lái)分析Vue2.x 響應(yīng)式原理的整體結(jié)構(gòu)。

如下圖所示:

我們接下來(lái),將根據(jù)這幅圖片描述的流程來(lái)實(shí)現(xiàn)一款迷你版Vue。Vue2.x采用了Virtual DOM,但是因?yàn)檫@里只需要實(shí)現(xiàn)一個(gè)迷你版,所以我們這里做了簡(jiǎn)化,我們這里就是直接操作DOM。

下面,我們來(lái)看下我是如何搭建一款Vue mini的。

第一步

頁(yè)面結(jié)構(gòu)如下,我們可以先引入Vue2.x完整版本,看下實(shí)現(xiàn)效果。

 
 
 
 
  1.     
  2.     
  3.     
  4.     Vue2.x Reactive
  5.     
  6.         

    文本節(jié)點(diǎn)

  7.         
    {{msg}}
  8.         
    {{count}}
  9.         
    {{obj.name}}
  10.         
    {{arr[0]}}
  11.         
    {{obj.inner.age}}
  12.         
    {{obj.inner.name}}
  13.         

    v-text

  14.         
  •         

    v-model

  •         
  •         
  •         

    v-html

  •         
  •         

    v-show

  •         {{isShow}}
  •         

    v-on

  •         handler
  •         onClick
  •         

    v-if

  •         
  •             {{isIf}}

  •         
  •     
  •     
  •     
  •  經(jīng)過(guò)測(cè)試,Vue2.x完整版搭載的頁(yè)面顯示如下。我們將使用Vue迷你版本同樣實(shí)現(xiàn)以下頁(yè)面效果。

    第二步

    我們將根據(jù)整體結(jié)構(gòu)圖和頁(yè)面結(jié)構(gòu)來(lái)搭建這個(gè)Vue迷你版本,我們姑且將這個(gè)版本叫做vuemini.js。

    通過(guò)整體結(jié)構(gòu)圖我們發(fā)現(xiàn),一共有Vue、Observer、Compiler、Dep、Watcher這幾個(gè)構(gòu)造函數(shù)。我們首先創(chuàng)建這幾個(gè)構(gòu)造函數(shù),這里不使用class類來(lái)定義是因?yàn)閂ue源碼大部分也使用構(gòu)造函數(shù),另外,相對(duì)也好拓展。

    Vue

     
     
     
     
    1. // 實(shí)例。
    2. function Vue(options) {
    3.     this.$options = options || {};
    4.     this._data = typeof options.data === 'function' ? options.data() : options.data || {};
    5.     this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
    6.     // 負(fù)責(zé)把data中的屬性注入到Vue實(shí)例,轉(zhuǎn)換成getter/setter
    7.     this._proxyData(this._data);
    8.     this.initMethods(this, options.methods || {})
    9.     // 負(fù)責(zé)調(diào)用observer監(jiān)聽(tīng)data中所有屬性的變化
    10.     new Observer(this._data);
    11.     // 負(fù)責(zé)調(diào)用compiler解析指令/插值表達(dá)式
    12.     new Compiler(this);
    13. }
    14. // 將data中的屬性掛載到this上
    15. Vue.prototype._proxyData = function (data) {
    16.     Object.keys(data).forEach(key => {
    17.         Object.defineProperty(this, key, {
    18.             configurable: true,
    19.             enumerable: true,
    20.             get() {
    21.                 return data[key]
    22.             },
    23.             set(newVal) {
    24.                 if (newVal === data[key]) {
    25.                     return
    26.                 }
    27.                 data[key] = newVal;
    28.             }
    29.         })
    30.     })
    31. }
    32. function noop(a, b, c) { }
    33. function polyfillBind(fn, ctx) {
    34.     function boundFn(a) {
    35.         var l = arguments.length;
    36.         return l
    37.             ? l > 1
    38.                 ? fn.apply(ctx, arguments)
    39.                 : fn.call(ctx, a)
    40.             : fn.call(ctx)
    41.     }
    42.     boundFn._length = fn.length;
    43.     return boundFn
    44. }
    45. function nativeBind(fn, ctx) {
    46.     return fn.bind(ctx)
    47. }
    48. const bind = Function.prototype.bind
    49.     ? nativeBind
    50.     : polyfillBind;
    51. // 初始化methods屬性
    52. Vue.prototype.initMethods = function (vm, methods) {
    53.     for (var key in methods) {
    54.         {
    55.             if (typeof methods[key] !== 'function') {
    56.                 warn(
    57.                     "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
    58.                     "Did you reference the function correctly?",
    59.                     vm
    60.                 );
    61.             }
    62.         }
    63.         vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
    64.     }
    65. }

    Observer

     
     
     
     
    1. // 數(shù)據(jù)劫持。
    2. // 負(fù)責(zé)把data(_data)選項(xiàng)中的屬性轉(zhuǎn)換成響應(yīng)式數(shù)據(jù)。
    3. function Observer(data) {
    4.     this.walk(data);
    5. }
    6. Observer.prototype.walk = function (data) {
    7.     if (!data || typeof data !== 'object') {
    8.         return
    9.     }
    10.     Object.keys(data).forEach(key => {
    11.         this.defineReactive(data, key, data[key]);
    12.     })
    13. }
    14. Observer.prototype.defineReactive = function (obj, key, val) {
    15.     let that = this;
    16.     // 負(fù)責(zé)收集依賴
    17.     let dep = new Dep();
    18.     // 如果val是對(duì)象,把val內(nèi)部的屬性轉(zhuǎn)換成響應(yīng)式數(shù)據(jù)
    19.     this.walk(val);
    20.     Object.defineProperty(obj, key, {
    21.         enumerable: true,
    22.         configurable: true,
    23.         get() {
    24.             // 收集依賴
    25.             Dep.target && dep.addSub(Dep.target)
    26.             return val
    27.         },
    28.         set(newVal) {
    29.             if (newVal === val) {
    30.                 return
    31.             }
    32.             val = newVal;
    33.             // data內(nèi)屬性重新賦值后,使其轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)。
    34.             that.walk(newVal);
    35.             // 發(fā)送通知
    36.             dep.notify();
    37.         }
    38.     })
    39. }

    Compiler

     
     
     
     
    1. // 編譯模板,解析指令/插值表達(dá)式
    2. // 負(fù)責(zé)頁(yè)面的首次渲染
    3. // 當(dāng)數(shù)據(jù)變化時(shí)重新渲染視圖
    4. function Compiler(vm) {
    5.     this.el = vm.$el;
    6.     this.vm = vm;
    7.     // 立即編譯模板
    8.     this.compile(this.el);
    9. }
    10. // 編譯模板,處理文本節(jié)點(diǎn)和元素節(jié)點(diǎn)
    11. Compiler.prototype.compile = function (el) {
    12.     let childNodes = el.childNodes;
    13.     Array.from(childNodes).forEach(node => {
    14.         // 處理文本節(jié)點(diǎn)
    15.         if (this.isTextNode(node)) {
    16.             this.compileText(node);
    17.         }
    18.         // 處理元素節(jié)點(diǎn) 
    19.         else if (this.isElementNode(node)) {
    20.             this.compileElement(node);
    21.         }
    22.         // 判斷node節(jié)點(diǎn),是否有子節(jié)點(diǎn),如果有子節(jié)點(diǎn),要遞歸調(diào)用compile方法
    23.         if (node.childNodes && node.childNodes.length) {
    24.             this.compile(node);
    25.         }
    26.     })
    27. }
    28. // 編譯文本節(jié)點(diǎn),處理插值表達(dá)式
    29. Compiler.prototype.compileText = function (node) {
    30.     // console.dir(node);
    31.     let reg = /\{\{(.+?)\}\}/;
    32.     let value = node.textContent;
    33.     if (reg.test(value)) {
    34.         let key = RegExp.$1.trim();
    35.         if (this.vm.hasOwnProperty(key)) {
    36.             node.textContent = value.replace(reg, typeof this.vm[key] === 'object' ? JSON.stringify(this.vm[key]) : this.vm[key]);
    37.             // 創(chuàng)建watcher對(duì)象,當(dāng)數(shù)據(jù)改變更新視圖
    38.             new Watcher(this.vm, key, (newVal) => {
    39.                 node.textContent = newVal;
    40.             })
    41.         } else {
    42.             const str = `this.vm.${key}`;
    43.             node.textContent = value.replace(reg, eval(str));
    44.             // 創(chuàng)建watcher對(duì)象,當(dāng)數(shù)據(jù)改變更新視圖
    45.             new Watcher(this.vm, key, () => {
    46.                 const strw = `this.vm.${key}`;
    47.                 node.textContent = value.replace(reg, eval(strw));
    48.             })
    49.         }
    50.     }
    51. }
    52. // 判斷節(jié)點(diǎn)是否是文本節(jié)點(diǎn)
    53. Compiler.prototype.isTextNode = function (node) {
    54.     return node.nodeType === 3;
    55. }
    56. // 判斷節(jié)點(diǎn)是否是元素節(jié)點(diǎn)
    57. Compiler.prototype.isElementNode = function (node) {
    58.     return node.nodeType === 1;
    59. }
    60. // 編譯元素節(jié)點(diǎn),處理指令
    61. Compiler.prototype.compileElement = function (node) {
    62.     // console.log(node.attributes);
    63.     // 遍歷所有的屬性節(jié)點(diǎn)
    64.     Array.from(node.attributes).forEach(attr => {
    65.         let attrName = attr.name;
    66.         // console.log(attrName);
    67.         // 判斷是否是指令
    68.         if (this.isDirective(attrName)) {
    69.             // 判斷:如v-on:click
    70.             let eventName;
    71.             if (attrName.indexOf(':') !== -1) {
    72.                 const strArr = attrName.substr(2).split(':');
    73.                 attrName = strArr[0];
    74.                 eventName = strArr[1];
    75.             } else if (attrName.indexOf('@') !== -1) {
    76.                 eventName = attrName.substr(1);
    77.                 attrName = 'on';
    78.             } else {
    79.                 attrName = attrName.substr(2);
    80.             }
    81.             let key = attr.value;
    82.             this.update(node, key, attrName, eventName);
    83.         }
    84.     })
    85. }
    86. // 判斷元素屬性是否是指令
    87. Compiler.prototype.isDirective = function (attrName) {
    88.     return attrName.startsWith('v-') || attrName.startsWith('@');
    89. }
    90. // 指令輔助函數(shù)
    91. Compiler.prototype.update = function (node, key, attrName, eventName) {
    92.     let updateFn = this[attrName + 'Updater'];
    93.     updateFn && updateFn.call(this, node, this.vm[key], key, eventName);
    94. }
    95. // 處理v-text指令
    96. Compiler.prototype.textUpdater = function (node, value, key) {
    97.     node.textContent = value;
    98.     new Watcher(this.vm, key, (newVal) => {
    99.         node.textContent = newVal;
    100.     })
    101. }
    102. // 處理v-html指令
    103. Compiler.prototype.htmlUpdater = function (node, value, key) {
    104.     node.insertAdjacentHTML('beforeend', value);
    105.     new Watcher(this.vm, key, (newVal) => {
    106.         node.insertAdjacentHTML('beforeend', newVal);
    107.     })
    108. }
    109. // 處理v-show指令
    110. Compiler.prototype.showUpdater = function (node, value, key) {
    111.     !value ? node.style.display = 'none' : node.style.display = 'block'
    112.     new Watcher(this.vm, key, (newVal) => {
    113.         !newVal ? node.style.display = 'none' : node.style.display = 'block';
    114.     })
    115. }
    116. // 處理v-if指令
    117. Compiler.prototype.ifUpdater = function (node, value, key) {
    118.     const nodew = node;
    119.     const nodep = node.parentNode;
    120.     if (!value) {
    121.         node.parentNode.removeChild(node)
    122.     }
    123.     new Watcher(this.vm, key, (newVal) => {
    124.         console.log(newVal);
    125.         !newVal ? nodep.removeChild(node) : nodep.appendChild(nodew);
    126.     })
    127. }
    128. // 處理v-on指令
    129. Compiler.prototype.onUpdater = function (node, value, key, eventName) {
    130.     if (eventName) {
    131.         const handler = this.vm.$options.methods[key].bind(this.vm);
    132.         node.addEventListener(eventName, handler);
    133.     }
    134. }
    135. // 處理v-model指令
    136. Compiler.prototype.modelUpdater = function (node, value, key) {
    137.     node.value = value;
    138.     new Watcher(this.vm, key, (newVal) => {
    139.         node.value = newVal;
    140.     })
    141.     // 雙向綁定,視圖變化更新數(shù)據(jù)
    142.     node.addEventListener('input', () => {
    143.         this.vm[key] = node.value;
    144.     })
    145. }

    Dep

     
     
     
     
    1. // 發(fā)布者。
    2. // 收集依賴,添加所有的觀察者(watcher)。通知所有的觀察者。
    3. function Dep() {
    4.     // 存儲(chǔ)所有的觀察者watcher
    5.     this.subs = [];
    6. }
    7. // 添加觀察者
    8. Dep.prototype.addSub = function (sub) {
    9.     if (sub && sub.update) {
    10.         this.subs.push(sub);
    11.     }
    12. }
    13. // 發(fā)送通知
    14. Dep.prototype.notify = function () {
    15.     this.subs.forEach(sub => {
    16.         sub.update();
    17.     })
    18. }

    Watcher

     
     
     
     
    1. function Watcher(vm, key, cb) {
    2.     this.vm = vm;
    3.     this.key = key;
    4.     this.cb = cb;
    5.     // 把當(dāng)前watcher對(duì)象記錄到Dep類的靜態(tài)屬性target
    6.     Dep.target = this;
    7.     if (vm.hasOwnProperty(key)) {
    8.         this.oldVal = vm[key];
    9.     } else {
    10.         const str = `vm.${key}`;
    11.         this.oldVal = eval(str);
    12.     }
    13.     Dep.target = null;
    14. }
    15. // 當(dāng)數(shù)據(jù)發(fā)生變化的時(shí)候更新視圖
    16. Watcher.prototype.update = function () {
    17.     let newVal;
    18.     if (this.vm.hasOwnProperty(this.key)) {
    19.         newVal = this.vm[this.key];
    20.     } else {
    21.         const str = `this.vm.${this.key}`;
    22.         newVal = eval(str);
    23.     }
    24.     this.cb(newVal);
    25. }

    以上這幾個(gè)構(gòu)造函數(shù)就實(shí)現(xiàn)了我們所說(shuō)的迷你版本,將它們整合成一個(gè)文件vuemini.js。在上面所提示的頁(yè)面引入,查看效果。

    另外,我在data中綁定了一個(gè)html屬性,值為一個(gè)'

    {{msg}}
    ',與之前完整版相比,圖中的v-html下方的maomin文本也被渲染出來(lái)。

    尤大開(kāi)發(fā)的Vue2.x迷你版本

    下面,我們將看下尤大開(kāi)發(fā)的迷你版本,這個(gè)版本引入了Virtual DOM,但是主要是針對(duì)響應(yīng)式式原理的,可以根據(jù)尤大的迷你版本與上面的版本作個(gè)比較,可以看下有哪些相似之處。

     
     
     
     
    1.     
    2.     
    3.     
    4.     vue2mini
    5.     
  •