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,792 Responses

  1. Richardevics表示:

    minocycline 50mg tablets for humans for sale buy online what does minocycline treat

  2. sex chat表示:

    This is a topic that is near to my heart… Cheers! Exactly where are your contact details though?

  3. ЖК Астро ЖК Теплый дом ЖК Счастье эти жк застройщика Паритет девелопмент
    который вводит в заблуждение своих дольщиков, некачественно строит и отказывается устранять замечания: например он трещины на раме заделывает скотчем. Все покажу расскажу – @dontcheatpeople – телеграмм.

  4. Jorgeguase表示:

    Elon Bet Casino’s interface works perfectly on my tablet, so I can play anywhere.
    elon bet casino

  5. Carlostague表示:

    Can these ultra-exclusive luxury destinations help extend your life? They’d certainly like to try
    pin-up casino withdrawal time
    When the Six Senses Residences Dubai Marina is completed in 2028, the gleaming 122-story building will be the tallest residential structure in the world, complete with luxury fitness and wellness amenities to match. Residents will be able to lift weights, take an outdoor yoga class or swim laps in a pool more than 100 stories high in the clouds.

    But what if, by living there, people were also extending their lives? That’s the mission of the “longevity floor,” another amenity available to future residents of the Six Senses’ 251 apartments and “sky mansions.” This unique floor will include even more specialized offerings such as crystal sound healing, believed by its practitioners to reduce stress and improve sleep. Or residents can indulge in hyperbaric treatments, breathing in 100% oxygen in a pressurized chamber which has shown promising anti-aging results.

    “The idea around it is that you’re not just purchasing a residence, you’re purchasing a lifestyle,” said Kevin Cavaco, director of marketing for Select Group, the building’s developer.

    “You’re purchasing an opportunity to work on your true wealth — which is your longevity. You’re prolonging your time.”

    Life extension may be a lofty — and dubious — pitch, but it’s a common theme among luxury fitness clubs, opulent new high rises and exclusive retreats. The trend coincides with new scientific studies and a parallel fixation in the tech world, but the provable science behind these promises is often murky.
    Celebrity personal trainer and gym designer Harley Pasternak is used to designing programs for high-profile celebrities including Kim Kardashian, Lady Gaga and Halle Berry. But he’s noticed a shift in the past few years, he told CNN over email, as he’s gained an “influx” of tech founder clients.

    “All of them are definitely more interested in aging, in a way that I’ve never seen prior to five years ago,” he said. “All kinds of biohacking tricks like heat exposure, cold, exposure, certain supplements, training, foraging, and even certain medications.”

  6. Сервисный центр предлагает стоимость ремонта кофемашины bosch починка кофемашин bosch

  7. Travismut表示:

    plavix medication: clopidogrel – generic plavix

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

  9. Charleszed表示:

    buy plavix: plavix price – п»їplavix generic

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

  11. Прошу обратить внимание на обман застройщика Паритет Девелопмент, который обманом продает свои квартиры, вы не получите ровным счетом ничего обещанного их отделом продаж. Посмотрите отзывы реальных покупателей их ЖК Резиденция лайф обещали бизнес класс и есть куча брошюр, буклетов, а на самом деле это ЖК эконом класса. Если есть альтернатива рассмотрите ее! @dontcheatpeople – телеграмм.

  12. AntonioQuaps表示:

    перейти на сайт https://bs2site.is

  13. Diplomi_lvma表示:

    купить бланк диплома landik-diploms.ru .

  14. Sazrnug表示:

    Официальная покупка диплома вуза с упрощенной программой обучения

    instantguestpost.com/blog/kupit-diplom-991249bqs

  15. Trenttat表示:

    https://stromectol1st.shop/# ivermectin 4 tablets price
    best cure for ed

  16. Arthurfrunc表示:

    https://stromectol1st.shop/# purchase stromectol
    top 10 online pharmacy in india

  17. Travismut表示:

    more: rybelsus generic – rybelsus cost

  18. DonaldDurce表示:

    The magical white stone wonderland with effervescent bathing pools
    1xbet mobile casino
    From a distance, Pamukkale looks every bit like a ski resort, with a cascade of brilliant white slopes and a scattering of tourists at the top, seemingly preparing to slalom down into the valley below.

    So why isn’t it melting away as midsummer temperatures nudge toward 100 Fahrenheit, or 37 Celsius, and the heat hangs in the shimmering air?

    Because this unusual and beautiful wonder, located deep in the sunkissed hills of southwestern Turkey, isn’t snow at all. In fact the water it’s formed from sometimes spurts out of the ground at boiling point.

    And those visitors milling around its upper reaches aren’t going anywhere fast. Most are here to take in the extraordinary spectacle – and either paddle or soak in some of the planet’s most photogenic pools.

    Today, Pamukkale’s travertine limestone slopes and pools, filled with milky blue mineral water, are perfect for Instagram moments, especially as the magic hour evening sun casts their rippled surfaces in hues of pink.

    Gateway to Hell
    But this place was a tourist sensation thousands of years before social media, as first Greeks, then Romans flocked here for the thermal waters and to pay tribute at what was revered as a gateway to Hell.

    Today, Pamukkale and the ancient city of Hierapolis, which sprawls across the plateau above the white terraces, are part of a UNESCO World Heritage site that pulls in coachloads of visitors. Typically, many visit for a couple of hours, but it’s worth spending at least a day in this geological and historical playground.

  19. Sazrdfd表示:

    Диплом пту купить официально с упрощенным обучением в Москве

    1russa-diploms.ru

  20. Charleszed表示:

    minocycline 100mg over the counter: buy online – ivermectin 3mg dose

  21. Jorgeguase表示:

    The VIP program at Elon Bet Casino offers amazing rewards and exclusive bonuses for loyal players. elon casino

  22. Nilda Lazalde表示:

    The words are like seeds, planting ideas that blossom into understanding and appreciation.

  23. Emmett Krotz表示:

    Every piece you write is like adding another book to my mental library. Thanks for expanding my collection.

  24. The posts are like a cozy nook, inviting and comfortable, where I can immerse myself in thoughts.

  25. Malik Schell表示:

    A perfect blend of informative and entertaining, like the ideal date night conversation.

  26. Shanti Rhome表示:

    The Writing is like a favorite coffee shop where the drinks are always warm and the atmosphere is inviting.

  27. Domenic Nosis表示:

    This post has been incredibly helpful to me. The guidance is something I’m truly grateful for.

  28. The work is truly inspirational. I appreciate the depth you bring to The topics.

發佈留言

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