vue.js 學習手冊 框架的選擇與導入

這篇文章是vue.js學習手冊的第一篇文章,也是我認為最難寫的一篇文章,就像vue.js提到的他是一個“漸進式”框架,在這篇文章也想要跟各位分享選擇框架的一些原則,讓大家可以“漸進式”的了解為什麼我們在網頁開發時需要選擇一個框架來幫助我們,在選擇框架之前我們要先弄清楚,框架究竟可以幫助我們在網頁開發上的哪些部分,如果這些部分跟你要開發的項目並不媒合,那奉勸你別把單純的事情搞複雜了,而且你可能會開始討厭學習框架,但若反之,你一定會愛上框架,甚至覺得他讓你事半功倍。

強大的前、後端串接功能


現代的網頁被要求除了有著摩登的前端UI之外,在網頁中的資料有常需要配合“大數據”下的資料進行呈現,說白話一點也就是網頁上面呈現的資料並不是寫死在頁面中的,而是透過後端資料庫取出來的,舉凡會員登入的名稱、購物網站中的商品資訊、新聞網站中的新聞就連你現在看到的這篇文章,也都是存放於資料庫中,網頁去對資料庫進行讀取後顯示在介面上的。

當然除了對資料庫進行讀取之外,網頁也會對資料庫進行儲存的動作,舉凡會員資料修改、商品訂單建立、網站偏好設定…等等,而框架在這方面有許多很好的方法,讓我們可以更周全快速的處理這方面的動作,節省許多開發的時間與減少Bug上的產生。

模組化開發架構


在一個大型網站中,可能有許多網頁中會出現相同風格的元素,例如:下拉式選單、按鈕、分頁導覽,是每一個頁面都會重複應用到的一些元件,傳統的網頁開發上就是在每一頁嵌入對應的HTML Code,這樣的做法非但不易維護,也會增加許多冗長且重複的程式碼。

模組化開發可以如上圖所示,將頁面中需重用的元素拉出來設計成一個Component,在不同頁面可以透過引入的方式置入該Component,而Component的維護可以統一在該Component中進行,可以減少大量維護上的時間。

透過 Virtual DOM 來提升頁面效能


現代的網頁前端框架為了提升頁面操作的效能都提供了Virtual DOM,在Vue.js 2.0中也引入Virtual DOM,比Vue.js 1.0的初始渲染速度提升了2~4倍,並大大降低了內存消耗,至於為何Virtual DOM能提昇網頁的效能,大家就必須了解我們透過Javascirpt更新實體DOM時會產生的效能問題開始了解。

實體DOM更新的效能測試

這邊製作一個簡單的範例對實體DOM和虛擬DOM的效能進行說明:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>
<body>
  <div class="wrapper">
    <div class="container">
      <div class="itemList">
        <ul id="itemList__ul">
          <li id="liID">Item 1</li>
        </ul>
      </div>
    </div>
    <button onClick="insertItems()">Go</button>
  </div>
</body>
</html>
<script>
  var itemData = "";
  function insertItems() {
    for (var i = 1; i <= 100000; i++) {
      itemData = "Item " + i
      document.getElementById("liID").innerHTML = itemData;
    }
  }
</script>

在HTML DOM的操作上,只要頁面元素有變更,就可能會觸發Reflow或Repaint這樣的動作,瀏覽器也會耗費相當多的資源在進行這些動作,以上述的例子來看,當我們按下頁面上的按鈕之後,就會透過迴圈去改變li的內容,這樣將會觸發多次的瀏覽器動作。

下圖是我們在Chrome中獲得的效能資訊:

若是我們將上述程式中的第26行移除,則效能會改變如下圖所示:

這樣可以很明確的了解效能殺手就是程式中的第26行,而這行程式的目的是去更新瀏覽器中的內容,若沒有這行沒辦法讓使用者看到最終的結果,因為我們必須透過這樣的方式更新DOM內容。

虛擬DOM的效能測試

同樣頁面的效果,我們在Vue裡面的作法如下:

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <ul>
      <li v-for="item in items">{{ item.message }}</li>
    </ul>
    <button @click="insertItems">Go</button>
  </div>
</body>
</html>
<script>
    var vueData = {
        items: [
      { message: 'Item 1' }
    ]
    }
    var app = new Vue({
        el: '#app',
        data: vueData,
    methods: {
      insertItems: function(){
        for(var i = 1; i <= 100000; i ++){
          vueData.items[0].message = "Item " + i;
        }
      }
    }
    })
</script>

同樣的結果在Vue會在Javascript和瀏覽器中加入一層Virturl DOM,待Virturl DOM更新完畢之後,在寫入瀏覽器中。

透過這樣的方法,使用這得到的一樣的效果,但大大提高了使用者端瀏覽器的效能,可以從下圖觀察的出來!

在Virtual DOM的架構中,會把程式的動作動作集中在Virtual DOM中運算,當確定整個頁面結構之後,再一次性地將結果繪製到頁面中,可以想像成原本的DOM操作就是在每一次在CPU運算之後,直接把結果寫到硬碟當中,而Virtual DOM就是在CPU與硬碟間加入了記憶體層,CPU運算後先將結果儲存在記憶體中,最後再將記憶體的資料一次性的寫入硬碟

PS:記憶體的運算速度超過硬碟很多倍。

結論


綜合上述所說,網頁專案中採用前端框架,有著減少開發時間、易於維護、增加頁面效能…等優點,但若你的專案並不會大量與後端串接、製作上元件重複使用的機會不高、在頁面中也不太會對DOM進行Reflow與Repaint,可能是一個活動網頁、公司形象網頁…等,也許就沒有必要去選用一個前端框架,簡言之工具用在正確的地方,才能顯現出它的價值,當然目前符合使用框架的專案也一定非常多,也就是這樣的原因,才會造成前端框架的流行。

You may also like...

112,508 Responses

  1. Kennethslity表示:

    https://generic100mgeasy.com/# Generic 100mg Easy

  2. URL - nmy表示:

    Feel the adrenaline of 4rabet online gaming with quick login through the 4rabet platform. Whether you enjoy placing bets on 4rabet or virtual casino action, this site provides everything under one roof. Get the 4rabet mobile app for fast and easy access to your favorite games . Explore the 4rabet official website today and dive into the world of 4ra bet excitement . Sign up with 4rabet and elevate your casino fun to the next level !

    Enjoy the adrenaline rush of online gaming with 4rabet, your ultimate platform for wagering on sports and thrilling bets in India. Whether you love basketball or a variety of games, the 4rabet official website offers a easy-to-use system to wager online and win big . With the mobile access to 4rabet , you can access your betting profile anytime , anywhere , ensuring you never miss out . The 4rabet casino is created to serve both new players and experts , providing a diverse selection of wagering opportunities and casino games .

    Join the 4rabet online community today and experience a safe , intuitive gaming environment . Whether you prefer using 4rabet on your computer or mobile , the 4rbet experience is unmatched . Kick off your betting experience with 4 ra bet and take your casino fun to another level !

    Link: https://fukkatsu.net/business/egao/

    The 4rabet platform offers a effortless experience for sports betting and betting lovers in India. With the easy account access process being quick and secure , members can access their betting dashboards without issues. The smartphone access guarantees accessibility for those on the go , allowing them to enjoy their favorite games . The 4rabet website provides a vast selection of wagering opportunities , including basketball, and many other games , designed for Indian bettors . The 4rabet online platform is easy to navigate , ensuring smooth access for both first-time players and experienced players to navigate . By checking out the 4rabet official website , users can take advantage of high-value promotions. The 4ra bet platform is known for its trusted service and fast payouts , guaranteeing a secure gaming experience . Whether you enjoy wagering on cricket or playing slots , 4rbet has something for everyone .

  3. TerryDus表示:

    https://tadalafileasybuy.com/# TadalafilEasyBuy.com

  4. GregoryJough表示:

    Kamagra Kopen Online: kamagra kopen nederland – kamagra kopen nederland

  5. Kennethslity表示:

    https://generic100mgeasy.com/# buy generic 100mg viagra online

  6. Dwayneseisa表示:

    sildenafil over the counter Generic 100mg Easy Generic100mgEasy

  7. WillieSor表示:

    kraken зайти – кракен сайт, kra31

  8. SheilaGot表示:

    РедМетСплав предлагает обширный выбор качественных изделий из редких материалов. Не важно, какие объемы вам необходимы – от небольших закупок до крупных поставок, мы гарантируем своевременную реализацию вашего заказа.
    Каждая единица изделия подтверждена соответствующими документами, подтверждающими их происхождение. Превосходное обслуживание – то, чем мы гордимся – мы на связи, чтобы разрешать ваши вопросы по мере того как находить ответы под особенности вашего бизнеса.
    Доверьте потребности вашего бизнеса специалистам РедМетСплав и убедитесь в множестве наших преимуществ
    Наша продукция:

    Изделия РёР· магния ISO-MC21320 – BS ISO 16220 РџРѕРєРѕРІРєР° магниевая ISO-MC21320 – BS ISO 16220 представляет СЃРѕР±РѕР№ высококачественный РїСЂРѕРґСѓРєС‚, разработанный для использования РІ различных отраслях, включая авиастроение Рё автомобильную промышленность. Этот материал обладает отличной прочностью Рё легкостью, что делает его идеальным для создания деталей, требующих высочайших стандартов. РџРѕРєРѕРІРєР° магниевая ISO-MC21320 – BS ISO 16220 обеспечивает надежность Рё долговечность, Р° также обладает высокой РєРѕСЂСЂРѕР·РёРѕРЅРЅРѕР№ стойкостью. РќРµ упустите шанс купить РџРѕРєРѕРІРєР° магниевая ISO-MC21320 – BS ISO 16220 Рё улучшить качество СЃРІРѕРёС… изделий.

  9. GregoryJough表示:

    TadalafilEasyBuy.com: TadalafilEasyBuy.com – TadalafilEasyBuy.com

  10. Kennethslity表示:

    https://kamagrakopen.pro/# Kamagra Kopen Online

  11. Dwayneseisa表示:

    sildenafil over the counter buy viagra here Generic100mgEasy

  12. SheilaGot表示:

    РедМетСплав предлагает внушительный каталог отборных изделий из ценных материалов. Не важно, какие объемы вам необходимы – от небольших закупок до крупных поставок, мы гарантируем оперативное исполнение вашего заказа.
    Каждая единица изделия подтверждена соответствующими документами, подтверждающими их происхождение. Опытная поддержка – то, чем мы гордимся – мы на связи, чтобы разрешать ваши вопросы и предоставлять решения под особенности вашего бизнеса.
    Доверьте ваш запрос специалистам РедМетСплав и убедитесь в множестве наших преимуществ
    поставляемая продукция:

    Лента магниевая 23 – ISO 503 РљСЂСѓРі магниевый 23 – ISO 503 – это высококачественный инструмент, предназначенный для обработки различных материалов. Этот РєСЂСѓРі обеспечивает отличную производительность Рё долговечность, что делает его незаменимым РІ профессиональных Рё домашних мастерских. Благодаря уникальной технологии производства, РљСЂСѓРі магниевый 23 – ISO 503 отличается высокой устойчивостью Рє РёР·РЅРѕСЃСѓ Рё перегреву. Если РІС‹ ищете надежное решение для СЃРІРѕРёС… задач, купить РљСЂСѓРі магниевый 23 – ISO 503 – правильный выбор. Доверьтесь качеству Рё эффективности данной продукции для достижения идеальных результатов.

  13. WilliamNop表示:

    Generic 100mg Easy: buy generic 100mg viagra online – buy generic 100mg viagra online

  14. TerryDus表示:

    http://generic100mgeasy.com/# Generic 100mg Easy

  15. WillieSor表示:

    kra29 сс – kra30 at, kra32.cc

  16. MarvinInget表示:

    кракен сайт – Kra31.cc, kraken войти

  17. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. BobbyViabe表示:

    <div class="grid-cols-1 grid gap-2.5 amp;_>_*]:min-w-0 !gap-3.5″>
    Recently, the world of exclusive timepieces has observed the appearance of an fascinating development – the advancement of super clone watches. These aren’t simply the cheap knockoffs of before but rather expertly made replicas that have reshaped the parallel luxury watch world. We should delve into this fascinating world where craftsmanship meets availability.

    Grasping the Super Clone Revolution
    The term super clone describes top-tier replica watches that have attained unparalleled degrees of perfection. In contrast to regular replicas, these timepieces seek to replicate every characteristic of their legitimate counterparts with outstanding exactness. The gap between modern super clones and the replicas of the earlier times is absolutely amazing.
    What genuinely sets a super clone watch different is its adherence to truthfulness in several key elements:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    Perfect dimensions that replicate the real watches down to the millimeter
    Advanced movements that reproduce the workings of prestigious timepieces
    Premium materials that imitate the aesthetic and handling of genuine watches
    Commitment to minute details that even collectors might have trouble to notice

    The appeal of these watches is obvious – they deliver the look and a significant portion of the operational characteristics of owning a premium timepiece without the excessive investment. For various fans, this provides an chance to experience masterful watchmaking craftsmanship that would in other circumstances be out of range.

    The Game-Changing 4130 Mechanism
    Driving the premium Daytona super clones sits the 4130 movement – a engineering marvel that has significantly lifted the bar for replica timepieces. This heart is especially created to replicate the esteemed chronograph movement present in genuine Rolex Daytona watches.
    What enables the clone 4130 movement notably extraordinary is its performance:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    It runs at 28,800 oscillations per hour, making the fluid seconds-hand flow hallmark of fine watches
    It offers a autonomy of about 72 hours
    The chronograph mechanisms perform identically to they work in the actual watches
    The movement layout visually matches the genuine article

    When watchmakers managed to successfully reproduce the 4130, it represented a transformative development for the super clone industry. Instantly, the operational gap between legitimate luxury watches and their elite replicas diminished noticeably.

    Highlight on Luxury Replicas
    The Cosmograph Daytona Gold-Faced Premium Replica
    Within the most desired super clones is the Daytona Gold Dial replica. These watches exhibit:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    A beautiful fusion of gold tones and stainless steel elements
    Premium ceramic bezels that protect against marks and deterioration
    Shimmering dials that capture the characteristic golden shimmer of the authentic

    What aficionados especially praise about the best Daytona clones is their commitment to subtle details like the excellence of the case-to-bracelet transitions where the bracelet meets the case, the perfection of the dial lettering, and the precision of the chronograph actuators.

    The Rolex Yacht-Master in Gold
    Yet another outstanding feat in the super clone world is the Yacht-Master 18k yellow gold replica. These watches offer:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    Complex bracelets that simulate the pleasantness and visuals of Rolex’s Oysterflex
    Bidirectional bezels with precisely applied markings
    Housings that remarkably recreate the authentic model’s signature silhouette

    The Yacht-Master replicas have grown remarkably desired for their impressive appearance and ergonomic wear, causing them top picks among those who appreciate the seafaring design of the real.

    Identifying Excellence in a Intricate Field
    Navigating the world of super clone watches calls for diligent examination and diligence. For buyers fascinated by investigating this field, several aspects are paramount:

    Investigating Reliable Suppliers
    The difference between a real super clone and a inferior replica is considerable. Connoisseurs often suggest:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    Studying dedicated forums where owners exchange their experiences
    Searching for in-depth reviews with high-resolution photographs
    Learning about the classification system that most connoisseurs use to grade replica quality

    Mechanism Verification
    The foundation of any watch is its internal workings, and this is notably true for replicas. When examining a Daytona clone, confirming the standard of its movement is crucial:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    Real 4130 clone movements will possess the correct configuration and functionality
    The chronograph mechanisms should run precisely
    The autonomy should match the characteristics of the real

    Construction Quality
    Premium super clones use resources that nearly mimic those present in real luxury watches:

    <ul class="amp;:not(:last-child)_ul]:pb-1 amp;:not(:last-child)_ol]:pb-1 list-disc space-y-1.5 pl-7″>
    Premium stainless steel that yields the correct density and tactile quality
    Clear crystals with proper anti-reflective applications
    Surface treatment processes that guard against abrasion and changing color

    The Greater Perspective
    The world of super clone watches functions in an intriguing space within watch hobby culture. While they aren’t genuine luxury timepieces, they form a intriguing meeting point of respect for watchmaking artistry and attainability.
    Many collectors see super clones as an opportunity to appreciate appearances and mechanisms they value but are unable to feasibly acquire due to expense or attainability. Many people see them as a way to preview various styles before potentially obtaining an real piece.
    It’s important mentioning that in numerous locations, owning replica watches for non-commercial use is legitimate, though marketing them as original pieces is typically not allowed. The moral aspects around replica watches remain a area of ongoing discourse within watch groups.

    In Closing
    The super clone watch trend embodies a significant evolution in how individuals engage with luxury watch creations. From the outstanding clone 4130 movement to the careful reproduction of famous models like the Daytona and Yacht-Master, these replicas have created their special space in watch passion.
    Whether you’re a interested observer or a collector contemplating venturing into this field, comprehending the expertise, limitations, and considerations involved delivers worthwhile context. The world of chronometry is immense and diverse, with super clones constituting just one remarkable segment of a multifaceted and varied culture around timepieces.
    While no imitation takes the place of the heritage, artistry, and financial merit of original luxury watches, the horological advancements of the top super clones remain an noteworthy testimony to the broad recognition for exceptional watchmaking design.
    https://www.google.com/imgres?q=beyond%20superclone&imgurl=https%3A%2F%2Fgenevar.co%2Fwp-content%2Fuploads%2F2025%2F03%2FClone-Rolex-Day-Date-Yellow-Gold-Diamond-36-mm-President-Front.webp&imgrefurl=https%3A%2F%2Fgenevar.co%2Fproduct%2Fbeyond-superclone-day-date-yellow-gold-diamond-36-mm-president%2F&docid=Jt-JccjtScwvjM&tbnid=bdDIDSJxUQLXrM&vet=12ahUKEwjCyZqjiauMAxUw_7sIHWX4EJoQM3oECBoQAA..i&w=1000&h=1000&hcb=2&itg=1&ved=2ahUKEwjCyZqjiauMAxUw_7sIHWX4EJoQM3oECBoQAA

  19. WilliamNop表示:

    kamagra jelly kopen: Officiele Kamagra van Nederland – kamagra jelly kopen

發佈回覆給「TolikIncap」的留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。