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

44,522 Responses

  1. JuliaamtaUby表示:

    На сайте http://smartporog.ru изучите каталог для того, чтобы приобрести подходящий вариант выпадающих порогов. Автоматические пороги станут оптимальным вариантом при условии, если не получается произвести установку обычных вариантов либо в данном случае они считаются нежелательными. Перед вами огромное количество интересных вариантов, среди которых вы выберете решение для себя. Они идеально подходят для дверей различных типов. Такие пороги отлично убирают преграду в полу. Конструкции справятся со сквозняками, а также повысят звукоизоляцию.

  2. Travismut表示:

    Plavix generic price: clopidogrel pro – Plavix generic price

  3. Arthurfrunc表示:

    http://stromectol1st.shop/# ivermectin 5
    top online pharmacy india

  4. Полезный сервис быстрого загона ссылок сайта в индексация поисковой системы – полезный сервис

  5. Trenttat表示:

    https://rybelsus.icu/# order Rybelsus
    ed medications online

  6. электрические карнизы купить http://elektrokarniz-dlya-shtor11.ru/ .

  7. Richardevics表示:

    rybelsus generic cheaper Buy semaglutide

  8. Kevinles表示:

    Have you ever heard of the Birkin bag? It’s a very famous bag. Lots of people desire one because it’s trendy. Yet, it is really expensive. That’s why numerous search for a Birkin Bag Dupe.

    The Enduring Allure of Hermès’ Iconic Birkin Handbags
    birking bag dupe
    The Birkin bag is made by Hermès. It’s recognized for its high quality. The bag is handmade and makes use of the most effective natural leather. It is likewise very stylish. Celebs like it. However, it can set you back greater than a vehicle!

    What’s a Budget-friendly Alternate to a Birkin Purse?

    A Birkin Bag Dupe is a bag that resembles a Birkin bag. It is much cheaper. Many brand names make these dupes. They attempt to resemble the genuine thing. But, they set you back a great deal less.

    Advantages of a Birkin Bag Dupe
    <a hrefhttps://www.pinterest.com/pin/1152640098374774112/
    Cheaper than the original Birkin bag

    Continues to be extremely fashionable

    Lots of selections readily available

    Easy to find

    Leading Birkin Bag Dupes You Should Consider

    Right here are some wonderful Birkin Bag Dupes. They are elegant and inexpensive.

    Brand name

    Rate

    Functions

    Brand A.

    $ 50.

    Looks extremely similar to Birkin.

    Brand name B.

    $ 70.

    Premium natural leather.

    Brand name C.

    $ 90.

    Numerous colors available.

    Brand A.

    Brand An uses a fantastic Birkin Bag Dupe. It costs just $50. The bag looks extremely comparable to the initial Birkin. It is a fantastic selection if you want to save money.

    Brand name B.

    Brand B gives a high-quality dupe. It sets you back $70. The leather used is great. This bag will certainly last a long time. It is perfect for those that want toughness.

    Brand C.

    Brand C provides numerous shades. Their bags cost $90. You can pick a color that you like. The bag is elegant and fashionable. It is a great selection for fashion enthusiasts.

    How to Spot an Excellent Birkin Bag Dupe.

    Not all dupes are good. Right here are some pointers to find a good one:.

    Inspect the material. It ought to really feel good.

    Look at the sewing. It should be cool.

    See if the bag holds its form.

    Compare to images of the genuine Birkin bag.

    Where to Purchase a Birkin Bag Dupe.

    You can find these dupes in several locations. On-line shops have a lot of alternatives. Some physical shops additionally offer them. Constantly read evaluations before acquiring. This helps you pick the very best one.

    Online Stores.

    Lots of sites offer Birkin Bag Dupes. Amazon and ebay.com have many options. You can likewise examine specialty shops. Always inspect the return plan. In this manner, you can return the bag if you don't like it.

    Physical Stores.

    Some stores in shopping malls sell Birkin Bag Dupes. Visit a few stores to compare. Take a look at the bags very closely. This aids you select the best one.

    Frequently Asked Questions.

    What Is A Birkin Bag Dupe?

    A Birkin bag dupe is an inexpensive choice that simulates the style of a genuine Birkin bag.

    How To Find A High Quality Birkin Dupe?

    Examine stitching, products, and hardware. Quality dupes closely look like the original design and workmanship.

    Are Birkin Dupes Legal To Buy?

    Yes, Birkin dupes are legal as long as they do not use counterfeit logos or trademarks.

    Where To Get Birkin Bag Dupes?

    You can locate Birkin fools online on web sites like Etsy, AliExpress, and numerous style boutiques.

    Final thought.

    A Birkin Bag Dupe gives you design without breaking the bank. They are an excellent way to enjoy fashion. See to it to pick a good quality dupe. You will look trendy and conserve cash.

  9. Travismut表示:

    generic plavix: clopidogrel – Plavix 75 mg price

  10. Trenttat表示:

    https://paxlovid1st.shop/# buy paxlovid online
    ed pills cheap

  11. Trefggp表示:

    Как официально приобрести аттестат 11 класса с минимальными затратами времени

    provocation.flybb.ru/viewtopic.php?f=4&t=365

  12. Richardevics表示:

    clopidogrel bisulfate 75 mg check clopidogrel pro Cost of Plavix without insurance

  13. Alcoshop表示:

    Алкошоп и Alcoshop — это идеальный выбор для тех, кто хочет заказать алкоголь в Москве. Доставка работает круглосуточно, что позволяет получить нужные напитки в любое время. Позвонив по номеру +74993433939, вы можете оформить заказ быстро и без лишних хлопот.

    Круглосуточная доставка через Алкошоп позволяет получить желаемый напиток в кратчайшие сроки. Вы можете обратиться в Alcoshop для заказа через интернет, что делает процесс максимально удобным. Сервис гарантирует оперативное получение заказа.

    Для заказа алкоголя в Москве круглосуточно на дом достаточно позвонить по номеру +74993433939. В Alcoshop доступен большой выбор алкоголя, что позволит найти нужный товар для любого случая. Доставка осуществляется с заботой о качестве и безопасности, делая каждый заказ без лишних ожиданий.

  14. Arthurfrunc表示:

    http://stromectol1st.shop/# minocycline interactions
    india online pharmacy

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

  16. Richardevics表示:

    paxlovid pharmacy best price on pills paxlovid cost without insurance

  17. Charleszed表示:

    paxlovid pill: paxlovid 1st – buy paxlovid online

  18. Lehavkpjk表示:

    Ищете надежный способ оформить деньги на карту? Мы рекомендуем лучшие условия для быстрого оформления.

  19. Travismut表示:

    acne minocycline: stromectol fast delivery – ivermectin lotion price

  20. Charleszed表示:

    buy clopidogrel online: check clopidogrel pro – Plavix generic price

  21. Trenttat表示:

    http://paxlovid1st.shop/# paxlovid india
    ed drugs list

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

  23. Trenttat表示:

    https://rybelsus.icu/# Semaglutide pharmacy price
    treatment for erectile dysfunction

發佈留言

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