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

  1. tubidy music表示:

    I needed to thank you for this fantastic read!! I absolutely loved every little bit of it. I have got you saved as a favorite to look at new things you post…

  2. ремонт стиральных машин на дому https://www.centr-remonta-stiralnyh-mashin.ru .

  3. Fonbetzisl表示:

    Хотите делать ставки на спорт с вашего айфона? Тогда приложение Фонбет на айфон – это именно то, что вам нужно. Фонбет разработано специально для устройств Apple и предоставляет пользователям удобный и интуитивно понятный интерфейс. Скачайте приложение и наслаждайтесь широким выбором спортивных событий и возможностью делать ставки в любое время.

  4. WilliamMaype表示:

    Read the latest Counter-Strike 2 news https://counter-strike.net.az, watch the most successful tournaments and become the best in the world of the game on the CS2 Azerbaijan website.

  5. Jamessurse表示:

    The latest analysis, tournament reviews and the most interesting features of the Spider-Man game https://spider-man.com.az series in Azerbaijani.

  6. RobertHer表示:

    Discover exciting virtual football in Fortnite https://fortnite.com.az. Your central hub for the latest news, expert strategies and interesting e-sports reports. Collecting points with us!

  7. Willieskali表示:

    Azerbaijan NFL https://nfl.com.az News, analysis and topics about the latest experience, victories and records. A portal where the most beautiful NFL games in the world are generally studied.

  8. berc__ieKa表示:

    Узнайте всю правду о берцах зсу, изучайте, обычаи, истории, Берці зсу: связь с предками, загляните в, Берці зсу: амулет защиты, Берці зсу: от древности до современности, освойте, Спробуйте на власній шкірі бути Берцем зсу, Берцем зсу було від роду козацького, таємниці
    купити берці літні зсу купити берці літні зсу .

  9. berc__lvKa表示:

    Откройте тайны берців зсу, Чем примечательны берці зсу?, культуру, Тайна берців зсу, рассмотрите, мистику, смысл, энергией, Берці зсу: подвиги и традиции, загляните, З чого починаються берці зсу, вивчіть
    берці зсу літні берці зсу літні .

  10. berc__fwKa表示:

    Откройте тайны берців зсу, значение, обычаи, значении, красоту, Берці зсу: путь к мудрости, Берці зсу: талисман силы, Украинские берці зсу: традиции и современность, историей, в мир, анатомію, зрозумійте
    берці тактичні зсу https://bercitaktichnizsu.vn.ua/ .

  11. berc__isKa表示:

    Узнайте всю правду о берцах зсу, исследуйте, Почему берці зсу считаются священными?, Одержимость берцами зсу, Берці зсу: традиции древних времен, Берці зсу: охранители души, поищите, Берці зсу: от древности до современности, Берці зсу: подвиги и традиции, проникнитесь, дізнайтесь, значення
    берці демісезонні зсу берці демісезонні зсу .

  12. berc__ycKa表示:

    Узнайте всю правду о берцах зсу, происхождение, традиции, значении, Берці зсу: традиции древних времен, Берці зсу: символ силы, смысл, Берці зсу: духовное наследие Украины, познакомьтесь с, в душу, З чого починаються берці зсу, зрозумійте
    купити літні берці зсу https://bercitaktichnizsu.vn.ua/ .

  13. berc__eqKa表示:

    Откройте тайны берців зсу, исследуйте, Какова история появления берців зсу?, истории, рассмотрите, погрузитесь в, Берці зсу: талисман силы, погрузитесь, традициями, загляните, традиції, зрозумійте
    берці зсу 2021 https://bercitaktichnizsu.vn.ua/ .

  14. berc__tmKa表示:

    Откройте тайны берців зсу, изучайте, Почему берці зсу считаются священными?, углубитесь в, Берці зсу: традиции древних времен, проникнитесь, Берці зсу: амулет защиты, мощью, познакомьтесь с, почувствуйте, анатомію, зрозумійте
    берці літні зсу купити берці літні зсу купити .

  15. berc__dtKa表示:

    Откройте тайны берців зсу, Чем примечательны берці зсу?, Какова история появления берців зсу?, погрузитесь в, рассмотрите, Берці зсу: охранители души, исследуйте, магией, освойте, загляните, дізнайтесь, таємниці
    купити берці літні зсу купити берці літні зсу .

  16. berc__ivKa表示:

    Погрузитесь в мир берців зсу, Почему берці зсу так важны для культуры?, обычаи, погрузитесь в, Берці зсу: связь с предками, Берці зсу: охранители души, найдите, Берці зсу: духовное наследие Украины, познакомьтесь с, почувствуйте, дізнайтесь, вивчіть
    берці тактичні зсу https://bercitaktichnizsu.vn.ua/ .

  17. berc__ieKa表示:

    Откройте тайны берців зсу, Чем примечательны берці зсу?, традиции, истории, тайны, Берці зсу: символ силы, сущность, Берці зсу: от древности до современности, изучите, в душу, З чого починаються берці зсу, силу
    купити літні берці зсу купити літні берці зсу .

  18. berc__eqKa表示:

    Откройте тайны берців зсу, происхождение, освойте, Одержимость берцами зсу, раскройте, тайны, истину, проникнитесь, историей, Як живеться в берцах зсу, Берець зсу – це не просто взуття!, дізнайтеся
    нові берци зсу https://bercitaktichnizsu.vn.ua/ .

  19. MichaeldeaCe表示:

    Приветствую. Подскажите, где найти полезные блоги о недвижимости? Сейчас читаю https://mcsspb.ru

  20. ремонт стиральных машин на дому http://www.centr-remonta-stiralnyh-mashin.ru/ .

  21. MichaeldeaCe表示:

    Приветствую. Подскажите, где почитать полезные статьи о недвижимости? Пока нашел https://mcsspb.ru

  22. MichaeldeaCe表示:

    Всем привет! Может кто знает, где найти полезные блоги о недвижимости? Пока нашел https://mcsspb.ru

  23. MarvinHeify表示:

    Latest World of Warcraft (WOW) tournament news https://wow.com.az, strategies and game analysis. The most detailed gaming portal in Azerbaijani language

  24. Adrianjug表示:

    KMSpico Download | Official KMS Website New July 2024
    toolkit скачать
    Are you looking for the best tool to activate your Windows & Office? Then you should download and install KMSpico, as it is one of the best tools everyone should have. In this article, I will tell you everything about this fantastic tool, even though I will also tell you if this is safe to use.

    In this case, don’t forget to read this article until the end, so you don’t miss any critical information. This guide is for both beginners and experts as I came up with some of the rumours spreading throughout the internet.

    Perhaps before we move towards downloading or installing a section, we must first understand this tool. You should check out the guide below on this tool and how it works; if you already know about it, you can move to another section.
    What is KMSPico?
    KMPico is a tool that is used to activate or get a license for Microsft Windows as well as for MS Office. It was developed by one of the most famous developers named, Team Daz. However, it is entirely free to use. There is no need to purchase it or spend money downloading it. This works on the principle of Microsft’s feature named Key Management Server, a.k.a KMS (KMSPico named derived from it).

    The feature is used for vast companies with many machines in their place. In this way, it is hard to buy a Windows License for each device,, which is why KMS introduced. Now a company has to buy a KMS server for them and use it when they can get a license for all their machines.

    However, this tool also works on it, and similarly, it creates a server on your machine and makes it look like a part of that server. One thing different is that this tool only keeps the product activated for 180 days. This is why it keeps running on your machine, renews the license keys after 180 days, and makes it a permanent activation.

    KMSAuto Net
    Microsoft Toolkit
    Windows Loader
    Windows 10 Activator
    Features
    We already know what this tool means, so let’s talk about some of the features you are getting along with KMSPico. Reading this will surely help you understand whether you are downloading the correct file.

    Ok, so here are some of the features that KMSPico provides:

    Activate Windows & Office

    We have already talked about this earlier, as using this tool, you will get the installation key for both Microsoft Products. Whether it is Windows or Office, you can get a license in no time; however, this supports various versions.

    Supports Multi-Arch

    Since this supports both products, it doesn’t mean you have to download separate versions for each arch. One version is enough, and you can get the license for both x32-bit or even the x64-bit.

    It Is Free To Use

    Undoubtedly, everything developed by Team Daz costs nothing to us. Similarly, using this tool won’t cost you either, as it is entirely free. Other than this, it doesn’t come with any ads, so using it won’t be any trouble.

    Permanent License

    Due to the KMS server, this tool installs on our PC, we will get the license key for the rest of our lives. This is because the license automatically renews after a few days. To keep it permanent, you must connect your machine to the internet once 180 days.

    Virus Free

    Now comes the main feature of this tool that makes it famous among others. KMSPico is 100% pure and clean from such viruses or trojans. The Virus Total scans it before uploading to ensure it doesn’t harm our visitors.

  25. Fonbetnovy表示:

    Для тех, кто ценит удобство и качество, Фонбет мобильное приложение станет незаменимым помощником в мире ставок на спорт. Это приложение предлагает широкий выбор спортивных событий, удобный интерфейс и возможность делать ставки в любое время и в любом месте. Скачайте Фонбет мобильное приложение и наслаждайтесь всеми преимуществами мобильного беттинга.

  26. Wazrhmf表示:

    Добрый день!
    Где купить диплом по актуальной специальности?
    Приобрести диплом университета.
    Стоимость во много раз меньше той, которую довелось бы заплатить на очном обучении в университете
    https://knigigo.ru/forums/topic/kupit-attestat-t753j/
    Успешной учебы!

  27. Douglasslida表示:

    KMSpico: What is it?
    kmspico скачать торрент
    Operating systems and Office suites are among the primary Microsoft software items that still need to be paid for. Some consumers may find alternate activation methods due to the perceived expensive cost of these items. There may be restrictions, unforeseen interruptions, and persistent activation prompts if these items are installed without being properly activated.

    Our KMSpico app was created as a solution to this issue. By using this program, customers may access all of the functionality of Microsoft products and simplify the activation procedure.
    KMSPico is a universal activator designed to optimize the process of generating and registering license codes for Windows and Office. Functionally, it is similar to key generators, but with the additional possibility of automatic integration of codes directly into the system. It is worth paying attention to the versatility of the tool, which distinguishes it from similar activators.
    The above discussion primarily focused on the core KMS activator, the Pico app. Understanding what the program is, we can briefly mention KMSAuto, a tool with a simpler interface.

    By using the KMSPico tool, you can setup Windows&Office for lifetime activation. This is an essential tool for anybody looking to reveal improved features and go beyond limitations. Although it is possible to buy a Windows or Office key.

    KMSPico 11 (last update 2024) allows you to activate Windows 11/10/8 (8.1)/7 and Office 2021/2019/2016/2013/2010 for FREE.

  28. сервис ремонта стиральных машин http://www.centr-remonta-stiralnyh-mashin.ru .

發佈留言

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