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...

128,583 Responses

  1. Michaelkig表示:

    darkmarket url dark markets 2025 dark web market

  2. Michaelkig表示:

    darknet drug store darknet markets 2025 darknet links

  3. Williecrady表示:

    Banyak kasino memiliki promosi untuk slot https://slotdemo.auction/# Slot memberikan kesempatan untuk menang besar

  4. YopihonHossy表示:

    Расходные материалы для печати по лучшим ценам на сайте https://adisprint.ru/ . Зайдите в каталог, и вы найдете СНПЧ, ПЗК, чернила, картриджи, тонер, бумага, промывочная жидкость, программаторы, пластик для 3D печати и множество других расходных материалов для принтеров. Мы также предлагаем широкий выбор запчастей для ремонта принтеров, включая термопленки, ремни, ролики и фьюзеры. Доставка осуществляется по всей России.

  5. JacobLoody表示:

    https://www.fortekb.ru/ – Закажите кухню на официальном сайте.

  6. Online casinos have completely transformed the world of gambling, making it more accessible, convenient, and thrilling than ever before. Gone are the days when gambling was limited to land-based establishments, as the full casino experience is accessible from desktops, tablets, and smartphones.

    The Appeal of Online Gambling
    There are many reasons why online casinos have gained massive traction. Perhaps the most appealing aspect is how easy it is to access games. While land-based casinos have restrictions, online platforms operate 24/7, letting players enjoy their favorite games at any time.

    One of the strongest attractions is the enormous range of gaming options available. Physical casinos may offer a few hundred games at best, but digital platforms feature thousands. Whether you love old-school slots or cinematic video games, there’s something for everyone.

    Stay updated with the latest casino news, exclusive bonuses, and expert tips—follow us luckyjet

    How Online Casinos Keep Players Engaged
    One of the biggest draws of online casinos is the generous promotions and bonuses. Signing up usually comes with exciting perks like extra cash or free slot spins. Regular players can take advantage of loyalty programs, cashback deals, and exclusive VIP rewards.

    Games of Chance vs. Games of Strategy
    Not all casino games are about luck—some demand strategic thinking and expertise. In games like poker, knowledge and tactics can give players a significant edge over less experienced opponents. If you prefer a fast-paced, unpredictable experience, slots and roulette provide thrilling, luck-based gameplay.

    How to Gamble Responsibly Online
    As exciting as online gambling can be, it’s essential to practice responsible gaming. Setting personal limits, managing your budget wisely, and avoiding chasing losses are key to enjoying online casinos safely. Reputable platforms also promote responsible gaming by offering tools like deposit limits, self-exclusion, and links to gambling support organizations.

    Share Your Casino Experience
    Are you an online casino enthusiast? What’s your go-to game? Tell us about your biggest wins or best casino moments!

  7. Meds information leaflet. Cautions.
    where can i get generic atarax without a prescription
    Best trends of pills. Read information here.

  8. sbcairzxo表示:

    Bubble Shooter Games! Pop 2024 se ejecuta en los siguientes sistemas operativos: iOS. Por favor, inicia sesión para comentar. Overall, Balloon Pop Bubble Wrap is a simple yet effective game that offers relaxation and entertainment for the entire family while promoting stress relief and mindfulness. 6Jugar Bubble Boxes : Match 3D con NoxPlayer desde PC más fácilmente This bubbly game is addictive, so you better be careful because the bubble magic starts to work once you shoot the balls! In this pop-up balloon game, users can enjoy various smashing pop modes that provide endless entertainment. The absence of ads during gameplay ensures a seamless experience for both children and adults alike. Bubble Shooter – Classic Pop Bubble Blast The Game I love the game but when I stop playing for 12-24 hours I can not reload the game. I get white screens or black screen that have nothing to tell me what I need to do. I have taken the game off then down loaded it again. Nothing helps. Very very frustrating. Well here I am another week of messing with game. The last straw was to nought when I finally got on I had lost 270 levels setting me back t the 300 . I am so over this. Will be deleting. It no longer hold a 4 star it’s down to one now.
    https://www.mazafakas.com/user/profile/5869027
    A classic MSX1 arcade game reminiscent to games like Space Invader, where your sole job is to prevent incoming missiles from destroying your world. © Lagged 2025 The first entry for MSXdev’17 contest that we are proud to share with you!!! Name of the game: SKULLrs Name of the group: digiconcrete En este artículo, enumeraremos diferentes formas de Descargar Balloon Buster en PC en una guía paso a paso. Entonces, antes de lanzarnos, veamos las especificaciones técnicas de Balloon Buster. Use of this site is subject to express terms of use. By continuing past this page, you agree to abide by the Terms of Service. The Guide is now complete. — GAME ITEMS & OBSTACLES —- Find satisfaction in our stress relief games as you engage in calming activities that melt away tension and leave you feeling refreshed. With smooth controls, you can easily navigate through our collection of Pop it antistress fidgets and relaxing slime games, finding the perfect activity to suit your mood and preferences. Mini Relaxing Game is the perfect escape from the hustle and bustle of daily life. Let go of stress and anxiety as you indulge in the best stress relief games, specially curated to provide you with moments of pure relaxation and joy.

  9. LutherCiz表示:

    Проблема зависимостей остаётся актуальной в современном обществе. С каждым годом увеличивается число людей, страдающих от алкоголизма, наркомании и других форм зависимостей, что негативно отражается на их жизни и благополучии близких. Зависимость — это не просто физическое заболевание, но и глубокая психологическая проблема. Для эффективного лечения требуется помощь профессионалов, способных обеспечить комплексный подход.
    Получить дополнительные сведения – vyvod iz zapoya s vyezdom na dom voronezh

  10. ThomasThype表示:

    Slot klasik tetap menjadi favorit banyak orang: bonaslot – bonaslot.site

  11. DavidCooth表示:

    http://slotdemo.auction/# Kasino di Bali menarik banyak pengunjung

  12. DavidCooth表示:

    https://garuda888.top/# Mesin slot digital semakin banyak diminati

  13. Williecrady表示:

    Jackpot progresif menarik banyak pemain http://bonaslot.site/# Kasino memastikan keamanan para pemain dengan baik

  14. DavidCooth表示:

    https://slotdemo.auction/# Kasino selalu memperbarui mesin slotnya

  15. Williecrady表示:

    Banyak pemain berusaha untuk mendapatkan jackpot http://preman69.tech/# Banyak pemain mencari mesin dengan RTP tinggi

  16. MichaelIncap表示:

    dark markets 2025 dark markets darknet markets url

  17. DavidCooth表示:

    http://bonaslot.site/# Pemain sering mencoba berbagai jenis slot

  18. Williecrady表示:

    Pemain bisa menikmati slot dari kenyamanan rumah https://slot88.company/# Mesin slot digital semakin banyak diminati

  19. DavidCooth表示:

    http://garuda888.top/# Slot dengan tema budaya lokal menarik perhatian

  20. MichaelIncap表示:

    tor drug market darknet market darkmarket 2025

  21. Dannyfut表示:

    dark web marketplaces darknet market darknet site

  22. Rodneytus表示:

    darkmarket darknet sites dark market 2025

  23. AcAdund表示:

    Your handwritten mark is more than just a formality—it’s a representation of your personality. Whether you need a stylish, bold, or professional look, we specialize in helping you design a signature that is both visually appealing and functional. Our skilled artists analyze your preferences and handwriting to deliver a unique signature that matches your identity. Elevate your personal or business brand with a signature crafted just for you!

  24. Dannyfut表示:

    darknet drug market darkmarket url dark markets

  25. Dannyfut表示:

    dark market link dark market dark web markets

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

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