亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

裝飾者模式在日常開(kāi)發(fā)中的縮影和vue中的使用詳解

 更新時(shí)間:2022年12月22日 10:48:44   作者:qb  
這篇文章主要為大家介紹了裝飾者模式在日常開(kāi)發(fā)中的縮影和vue中的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

一、日常開(kāi)發(fā)

裝飾者模式以其不改變?cè)瓕?duì)象,并且與原對(duì)象有著相同接口的特點(diǎn),廣泛應(yīng)用于日常開(kāi)發(fā)和主流框架的功能中。

1、數(shù)據(jù)埋點(diǎn)

假如我們開(kāi)發(fā)了一個(gè)移動(dòng)端網(wǎng)頁(yè),有圖書(shū)搜索、小游戲、音頻播放和視頻播放等主要功能,初期,我們并不知道這幾個(gè)功能用戶的使用規(guī)律。

有一天,產(chǎn)品經(jīng)理說(shuō),我想要各個(gè)功能用戶的使用規(guī)律,并且通過(guò)echarts繪制折線圖和柱狀圖,能加嗎?

這就加......

起初:

<button id="smallGameBtn">小游戲</button>
<script>
    var enterSmallGame = function () {
        console.log('進(jìn)入小游戲')
    }
    document.getElementById('smallGameBtn').onclick = enterSmallGame;
</script>

通過(guò)裝飾者模式增加數(shù)據(jù)埋點(diǎn)之后:

<button id="smallGameBtn">小游戲</button>
<script>
     Function.prototype.after= function (afterFn) {
        var selfFn = this;
        return function () {
            var ret = selfFn.apply(this, arguments)
            afterFn.apply(this.arguments)
            return ret
        }
    }
    var enterSmallGame = function () {
        console.log('進(jìn)入小游戲')
    }
    var dataLog = function () {
        console.log('數(shù)據(jù)埋點(diǎn)')
    }
    enterSmallGame = enterSmallGame.after(dataLog)
    document.getElementById('smallGameBtn').onclick = enterSmallGame;
</script>

定義Function.prototype.after函數(shù),其中通過(guò)閉包的方式緩存selfFn,然后返回一個(gè)函數(shù),該函數(shù)首先執(zhí)行selfFn,再執(zhí)行afterFn,這里也很清晰的可以看出兩個(gè)函數(shù)的執(zhí)行順序。

在當(dāng)前例子中,首先執(zhí)行進(jìn)入小游戲的功能,然后,再執(zhí)行數(shù)據(jù)埋點(diǎn)的功能。

可以看出,加了數(shù)據(jù)埋點(diǎn),執(zhí)行函數(shù)是enterSmallGame,不加也是。同時(shí),也未對(duì)函數(shù)enterSmallGame內(nèi)部進(jìn)行修改。

2、表單校驗(yàn)

假如,我們開(kāi)發(fā)了登錄頁(yè)面,有賬號(hào)和密碼輸入框。

我們知道,校驗(yàn)是必須加的功能。

不加校驗(yàn):

賬號(hào):<input id="account" type="text">
密碼:<input id="password" type="password">
<button id="loginBtn">登錄</button>
<script>
    var loginBtn = document.getElementById('loginBtn')
    var loginFn = function () {
        console.log('登錄成功')
    }
    loginBtn.onclick = loginFn;
</script>

通過(guò)裝飾者模式加校驗(yàn)之后:

賬號(hào):<input id="account" type="text">
密碼:<input id="password" type="password">
<button id="loginBtn">登錄</button>
<script>
    var loginBtn = document.getElementById('loginBtn')
    Function.prototype.before = function (beforeFn) {
        var selfFn = this;
        return function () {
            if (!beforeFn.apply(this, arguments)) {
                return;
            }
            return selfFn.apply(this, arguments)
        }
    }
    var loginFn = function () {
        console.log('登錄成功')
    }
    var validateFn = function () {
        var account = document.getElementById('account').value;
        var password = document.getElementById('password').value;
        return account && password;
    }
    loginFn = loginFn.before(validateFn)
    loginBtn.onclick = loginFn;
</script>

定義Function.prototype.before函數(shù),其中通過(guò)閉包的方式緩存selfFn,然后返回一個(gè)函數(shù),該函數(shù)首先執(zhí)行beforeFn,當(dāng)其返回true時(shí),再執(zhí)行afterFn。

在當(dāng)前例子中,首先執(zhí)行表單校驗(yàn)的功能,然后,提示登錄成功,進(jìn)入系統(tǒng)。

可以看出,加了表單校驗(yàn),執(zhí)行函數(shù)是loginFn,不加也是。同時(shí),也未對(duì)函數(shù)loginFn內(nèi)部進(jìn)行修改。

二、框架功能(vue)

1、數(shù)組監(jiān)聽(tīng)

vue的特點(diǎn)之一就是數(shù)據(jù)響應(yīng)式,數(shù)據(jù)的變化會(huì)改變視圖的變化。但是,數(shù)組中通過(guò)下標(biāo)索引的方式直接修改不會(huì)引起視圖變化,通過(guò)push、pop、shift、unshiftsplice等方式修改數(shù)據(jù)就可以。

這里我們只看響應(yīng)式處理數(shù)據(jù)的核心邏輯Observer

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data
  constructor (value: any) {
    if (Array.isArray(value)) {
       protoAugment(value, arrayMethods)
    }
  }
}

如果需要響應(yīng)式處理的數(shù)據(jù)滿足Array.isArray(value),則可通過(guò)protoAugment對(duì)數(shù)據(jù)進(jìn)行處理。

function protoAugment (target, src: Object) {
  target.__proto__ = src
}

這里修改目標(biāo)的__proto__ 指向?yàn)?code>src,protoAugment(value, arrayMethods)執(zhí)行的含義就是修改數(shù)組的原型指向?yàn)?code>arrayMethods:

import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
methodsToPatch.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]
  def(arrayMethods, method, function mutator (...args) {
    const result = original.apply(this, args)
    const ob = this.__ob__
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    if (inserted) ob.observeArray(inserted)
    // notify change
    ob.dep.notify()
    return result
  })
})

通過(guò)const arrayProto = Array.prototype的方式緩存Array的原型,通過(guò)const arrayMethods = Object.create(arrayProto)原型繼承的方式讓arrayMethods上繼承了Array原型上的所有方法。這里有定義了包含pushsplice等方法的數(shù)組methodsToPatch,循環(huán)遍歷methodsToPatch數(shù)組并執(zhí)行def方法:

export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

這里的目的是當(dāng)訪問(wèn)到methodsToPatch中的方法method的時(shí)候,先const result = original.apply(this, args)執(zhí)行的原始方法,獲取到方法的執(zhí)行結(jié)果result。然后通過(guò)switch (method) 的方式針對(duì)不同的方法進(jìn)行參數(shù)的處理,手動(dòng)響應(yīng)式的處理,并且進(jìn)行視圖重新渲染的通知ob.dep.notify()。

整個(gè)過(guò)程可以看出,是對(duì)數(shù)組的原型進(jìn)行了裝飾者模式的處理。目的是,針對(duì)push、popshift、unshiftsplice等方法進(jìn)行裝飾,當(dāng)通過(guò)這些方法進(jìn)行數(shù)組數(shù)據(jù)的修改時(shí),在執(zhí)行本體函數(shù)arrayProto[method]的同時(shí),還執(zhí)行了手動(dòng)響應(yīng)式處理和視圖更新通知的操作。

2、重寫(xiě)掛載

vue還有特點(diǎn)是支持跨平臺(tái),不僅可以使用在web平臺(tái)運(yùn)行,也可以使用在weex平臺(tái)運(yùn)行。

首先定義了公共的掛載方法:

// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

通過(guò)裝飾者模式處理平臺(tái)相關(guān)的節(jié)點(diǎn)掛載和模板編譯:

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)   
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  // 這里執(zhí)行緩存的與平臺(tái)無(wú)關(guān)的mount方法
  return mount.call(this, el, hydrating)
}

可以看出,在web平臺(tái)中先緩存公共的掛載方法。當(dāng)其處理完平臺(tái)相關(guān)的掛載節(jié)點(diǎn)和模板編譯等操作后,再去執(zhí)行與平臺(tái)無(wú)關(guān)的掛載方法。

總結(jié)

裝飾者模式,是一種可以首先定義本體函數(shù)進(jìn)行執(zhí)行。然后,在需要進(jìn)行功能添加的時(shí)候,重新定義一個(gè)用來(lái)裝飾的函數(shù)。

裝飾的函數(shù)可以在本體函數(shù)之前執(zhí)行,也可以在本體函數(shù)之后執(zhí)行,在某一天不需要裝飾函數(shù)的時(shí)候,也可以只執(zhí)行本體函數(shù)。因?yàn)楸倔w函數(shù)和通過(guò)裝飾者模式改造的函數(shù)有著相同的接口,而且也可以不必去熟悉本體函數(shù)內(nèi)部的實(shí)現(xiàn)。

以上就是裝飾者模式在日常開(kāi)發(fā)中的縮影和vue中的使用詳解的詳細(xì)內(nèi)容,更多關(guān)于vue 使用裝飾者模式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • vue中關(guān)于element的el-image 圖片預(yù)覽功能增加一個(gè)下載按鈕(操作方法)

    vue中關(guān)于element的el-image 圖片預(yù)覽功能增加一個(gè)下載按鈕(操作方法)

    這篇文章主要介紹了vue中關(guān)于element的el-image 圖片預(yù)覽功能增加一個(gè)下載按鈕,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Vue.js劃分組件的方法

    Vue.js劃分組件的方法

    這篇文章主要介紹了Vue.js劃分組件的方法,需要的朋友可以參考下
    2017-10-10
  • 前端vue+express實(shí)現(xiàn)文件的上傳下載示例

    前端vue+express實(shí)現(xiàn)文件的上傳下載示例

    本文主要介紹了前端vue+express實(shí)現(xiàn)文件的上傳下載示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • Vue項(xiàng)目部署的實(shí)現(xiàn)(阿里云+Nginx代理+PM2)

    Vue項(xiàng)目部署的實(shí)現(xiàn)(阿里云+Nginx代理+PM2)

    這篇文章主要介紹了Vue項(xiàng)目部署的實(shí)現(xiàn)(阿里云+Nginx代理+PM2),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-03-03
  • vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法

    vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法

    這篇文章主要介紹了vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • vue組件(全局,局部,動(dòng)態(tài)加載組件)

    vue組件(全局,局部,動(dòng)態(tài)加載組件)

    組件是Vue.js最強(qiáng)大的功能之一。組件可以擴(kuò)展HTML元素,封裝可重用的代碼。這篇文章主要介紹了vue組件(全局,局部,動(dòng)態(tài)加載組件),需要的朋友可以參考下
    2018-09-09
  • vue3+element?plus實(shí)現(xiàn)側(cè)邊欄過(guò)程

    vue3+element?plus實(shí)現(xiàn)側(cè)邊欄過(guò)程

    這篇文章主要介紹了vue3+element?plus實(shí)現(xiàn)側(cè)邊欄過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • 使用vue-router beforEach實(shí)現(xiàn)判斷用戶登錄跳轉(zhuǎn)路由篩選功能

    使用vue-router beforEach實(shí)現(xiàn)判斷用戶登錄跳轉(zhuǎn)路由篩選功能

    這篇文章主要介紹了vue使用vue-router beforEach實(shí)現(xiàn)判斷用戶登錄跳轉(zhuǎn)路由篩選,本篇文章默認(rèn)您已經(jīng)會(huì)使用 webpack 或者 vue-cli 來(lái)進(jìn)行環(huán)境的搭建,并且具有一定的vue基礎(chǔ)。需要的朋友可以參考下
    2018-06-06
  • 如何處理?Vue3?中隱藏元素刷新閃爍問(wèn)題

    如何處理?Vue3?中隱藏元素刷新閃爍問(wèn)題

    本文主要探討了網(wǎng)頁(yè)刷新時(shí),原本隱藏的元素會(huì)一閃而過(guò)的問(wèn)題,以及嘗試過(guò)的解決方案并未奏效,通過(guò)實(shí)例代碼介紹了如何處理?Vue3?中隱藏元素刷新閃爍問(wèn)題,感興趣的朋友跟隨小編一起看看吧
    2024-10-10
  • Vue中Quill富文本編輯器的使用教程

    Vue中Quill富文本編輯器的使用教程

    這篇文章主要介紹了Vue中Quill富文本編輯器的使用教程,包括自定義工具欄、自定義字體選項(xiàng)、圖片拖拽上傳、圖片改變大小等使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09

最新評(píng)論