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

  1. Herberttoure表示:

    Bruno Miguel Borges Fernandes https://manchester-united.brunofernandes-br.com was born on September 8, 1994 in Maia, Portugal.

  2. Dwainguast表示:

    Rodrygo Silva de Goes https://real-madrid.rodrygo-br.com, known simply as Rodrygo, emerged as one of the the brightest young talents in world football.

  3. DavidTerge表示:

    Daniel Alves https://paris-saint-germain.danielalves.net is a name that symbolizes the greatness of the world of football.

  4. Danrfng表示:

    Привет!
    Где заказать диплом специалиста?
    Мы предлагаем дипломы психологов, юристов, экономистов и других профессий по невысоким ценам.
    http://www.zombiepumpkins.com/forum/memberlist.php?sk=m&sd=d&start=25500

  5. WilliamDeeli表示:

    Привет!
    Наши специалисты предлагают выгодно приобрести диплом, который выполняется на оригинальной бумаге и заверен печатями, штампами, подписями официальных лиц. Документ пройдет лубую проверку, даже с применением профессиональных приборов. Решите свои задачи максимально быстро с нашим сервисом.
    msfo-soft.ru/msfo/forum/messages/forum28/topic9959/message278494/?result=new#message278494
    Удачи!

  6. LutherExase表示:

    Anderson Silva https://killer-bees-muay-thai-college.andersonsilva.net was born in 1975 in Curitiba Brazil. From a young age he showed an interest in martial arts, starting to train in karate at the age of 5.

  7. Diplomi_afkl表示:

    купить диплом санкт образованиях asxdiplomik24.ru .

  8. Diplomi_yckl表示:

    диплом о высшем образовании купить дешево диплом о высшем образовании купить дешево .

  9. Manrcpc表示:

    Добрый день!
    Где приобрести диплом по нужной специальности?
    Мы готовы предложить документы ВУЗов, расположенных на территории всей РФ. Можно купить диплом от любого заведения, за любой год, в том числе документы СССР. Дипломы выпускаются на бумаге самого высшего качества. Это дает возможность делать настоящие дипломы, которые не отличить от оригинала. Документы заверяются необходимыми печатями и подписями.
    Мы предлагаем дипломы любых профессий по выгодным ценам.
    diplomasx.com/otzyvy
    Рады оказать помощь!

  10. WilliamDeeli表示:

    Добрый день!
    Наши специалисты предлагают выгодно заказать диплом, который выполнен на бланке ГОЗНАКа и заверен печатями, штампами, подписями официальных лиц. Данный диплом способен пройти любые проверки, даже с применением специального оборудования. Достигайте своих целей быстро и просто с нашей компанией.
    lnx.hotelresidencevillateresaischia.com/casamicciola/index.php?option=com_k2&view=itemlist&task=user&id=439796
    Хорошей учебы!

  11. Wazrblp表示:

    Привет, друзья!
    Мы готовы предложить документы ВУЗов, которые находятся в любом регионе РФ. Можно приобрести диплом от любого учебного заведения, за любой год, указав актуальную специальность и оценки за все дисциплины. Документы выпускаются на бумаге самого высокого качества. Это позволяет делать государственные дипломы, которые невозможно отличить от оригиналов. Документы будут заверены необходимыми печатями и штампами.
    misstres.ru/forum/search.php?action=members&p=223&s=d&order=ASC

  12. Diplomi_dekl表示:

    диплом о высшем медицинском образовании купить диплом о высшем медицинском образовании купить .

  13. Uazrysp表示:

    Привет!
    Где купить диплом специалиста?
    mosfo.getbb.ru/viewtopic.php?f=12&t=911
    Хорошей учебы!

  14. Всем привет! Может кто знает, где почитать разные блоги о недвижимости? Сейчас читаю https://iskrb.ru

  15. I quite like looking through a post that can make people think. Also, thanks for allowing me to comment.

  16. Manrbbi表示:

    Добрый день!
    Где приобрести диплом по необходимой специальности?
    Мы готовы предложить документы институтов, расположенных на территории всей РФ. Можно заказать диплом от любого заведения, за любой год, указав необходимую специальность и оценки за все дисциплины. Дипломы делаются на бумаге самого высокого качества. Это дает возможность делать настоящие дипломы, которые не отличить от оригиналов. Документы заверяются необходимыми печатями и подписями.
    Мы изготавливаем дипломы любой профессии по доступным ценам.
    ast-diplomy.com/otzyvy
    Окажем помощь!

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

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

  19. Wazrtij表示:

    Добрый день!
    Мы готовы предложить документы техникумов, расположенных на территории всей России. Вы сможете приобрести качественно напечатанный диплом от любого учебного заведения, за любой год, указав актуальную специальность и хорошие оценки за все дисциплины. Дипломы и аттестаты делаются на бумаге высшего качества. Это дает возможность делать настоящие дипломы, не отличимые от оригинала. Они будут заверены необходимыми печатями и подписями.
    kingcityrp.moibb.ru/viewtopic.php?t=365

  20. Zazrunu表示:

    Здравствуйте!
    Заказать документ института вы имеете возможность в нашей компании в столице. Мы оказываем услуги по изготовлению и продаже документов об окончании любых университетов РФ. Вы получите необходимый диплом по любым специальностям, включая документы старого образца.
    cromia.ua/forum/user/5968/
    Успешной учебы!

  21. Всем привет! Подскажите, где найти разные статьи о недвижимости? Сейчас читаю https://iskrb.ru

  22. Lazrxge表示:

    Добрый день!
    Где заказать диплом специалиста?
    Приобрести диплом любого ВУЗа.
    aubameyangclub.com/read-blog/2036

  23. Zazrgzs表示:

    Добрый день!
    Купить документ о получении высшего образования вы можете в нашей компании. Мы предлагаем документы об окончании любых ВУЗов России. Вы сможете получить необходимый диплом по любой специальности, включая документы образца СССР.
    rsn360.ru/blogs/new
    Хорошей учебы!

  24. bestiptv1表示:

    Can I just say what a relief to discover somebody who genuinely knows what they are discussing on the net. You actually realize how to bring a problem to light and make it important. More people must check this out and understand this side of your story. I was surprised that you are not more popular because you certainly have the gift.

  25. DouglasJok表示:

    For people who love the charm of high-end purses but shudder at the hefty price, replica handbags provide an enticing option. This write-up reveals the intricacies of the imitation purse market, emphasizing its attraction to fashion lovers and luxury lovers alike. From understanding what fake purses are to suggestions for making wise purchases, we’ll discuss everything you require to learn to revel in fashion without busting the wallet.
    Replica bags represent premium imitations of designer handbags, designed to closely closely resemble the authentic versions. While these bags may never bear the official brand name, these replicas typically mirror the same style, materials, and quality of with their much expensive originals.
    http://tiny.cc/seq3yz
    Caliber plus Skill

    Contrary to common belief, many fake handbags are created with careful focus to details. Expert artisans utilize high-quality materials to guarantee the fact that the replicas have the comparable look and feel as the original designer items.

    Availability and Variety

    replica. latest.Ethical Considerations

    While fake bags provide an budget-friendly way to experience high-end style, it is important to acknowledge acknowledge the ethical implications. The production and distribution of fake fake bags may breach on IP rights, bringing up issues concerning the morality of buying and possessing such products.Access to Luxury Designs

    Motives Opt for Knockoff Bags?

    Fake purses have a notable significant following among fashion enthusiasts for several various compelling arguments. Below, we examine why such these chic options have grown become so liked.

    Budget-friendly

    One of the key key clear benefits of replica replica purses is. Premium replicas can offer the same same stylistic satisfaction as genuine genuine high-end purses without the the exorbitant high expense.

    Imitation bags enable it feasible for fashion enthusiasts to appreciate those newest high-end creations, irrespective to budget constraints. This availability allows more individuals to engage with haute couture to express their style.Experimentation Without Commitment

    For whom experiment with experimenting with with different styles, bags offer a way a way new various without without a long-term investment. Such versatility can be appealing appealing individuals individuals to switch up their their looks.How to Identify the High-Quality Imitation Bagplica bags.

    Exploring this imitation bag market can be tricky, however armed with proper correct information, you will easily execute smart purchases. Below exist several tips on identifying high-quality reproduction bags

    Material and Stitching

    Pay close attention to the materials used and the quality of the stitching. High-quality replicas often use genuine leather or premium synthetic alternatives and exhibit clean, precise stitching.

    Equipment and Information

    Inspect the hardware, such as zippers, clasps, and logos. Premium replicas have components that almost mimics that of the genuine luxury bags, with zero coarse edges or sloppily finished details.

    Although imitation purses are unable to legitimately employ the identical trademark of the authentic ones, a few may contain slight markings that imitate the pattern aspects of high-end brands. Search for these elements to judge the authenticity of the replica.Popular Replica Bag Brands

    Some labels are famous renowned for high-quality copies, giving clothing enthusiasts an diverse range of trendy choices. Here feature a few of the best top sought-after replica purse brands.

    AAA Bags Purses is known for producing producing a few of the top imitations on the market. Their products bags feature exceptional focus to precision and, making popular amongst imitation fans.

    Purse Valley Bags Products provides an extensive range of imitation bags, such as designs influenced by top top luxury brands. With a focus on quality and customer client happiness, they’ve built established a solid name in the copy handbag industry.

    Designer Discreet Bags specializes on creating high-quality copies that closely imitate the authentic versions. Their range features bags by legendary designers, giving style enthusiasts with ample plenty of options.

    The Art for Designing Imitation Bags

    Imitation purses can seamlessly blend into any collection, letting you to create chic and trendy ensembles. Below are some hints for incorporating fake bags into your style range.Handling with Care

    Combining with Timeless Outfits

    A timeless ensemble, such as a little black dress or a fitted suit, can be elevated with a thoughtfully picked replica bag. Opt for enduring styles that match your ensemble and infuse a dash of sophistication.

    Blending Haute and Casual Fashion

    Combine top-notch replica purses with budget-friendly fashion articles to create a harmonious and stylish look. This approach allows you to showcase your taste whilst remaining budget-conscious.

    Adorning using Confidence

    When matching replica handbags, assurance is key. Manage your fake purse with the same attention and respect as you would a genuine luxury item, and it will boost your entire appearance.

    Maintaining your Fake Handbag

    Correct maintenance and upkeep are essential to maintain your imitation handbag being its optimal. Adhere to these hints to maintain its longevity.

    Consistent Maintenance

    Wash your fake handbag frequently with a soft rag and gentle detergent. Steer clear of abrasive cleaners that can ruin the surface or color.

    Storing Hints

    Store your replica purse in a cool, dry place, not in immediate sun. Utilize protective bags or soft fabrics to shield it from dust and scratches.

    Handle your imitation purse with, keeping away from rough surfaces and overstuffing. This can assist maintain its shape while also preventing any harm.

    Replica handbags provide a budget-friendly alternative to luxury brand pieces without having to compromising fashion and quality. With proper styling and care, they can seamlessly integrate in any every style wardrobe, which makes them the favored choice among style enthusiasts. Whether you’re searching for a classic design & the fashionable statement-making item, there are numerous reputable imitation purse labels which offer high-quality options which fit any preference. Therefore go ahead and add a few fashionable replicas to your own collection – no one will be able to notice a difference.The Social Aspect of Replica Bags

    Treat your imitation handbag with proper care, avoiding overburdening it by heavy items. Doing so will help preserve the form & avoid wear & tear.

    Fake bags aren’t not about fashion; these also encourage a sense regarding community among fans. Here, we examine some social aspects regarding having and discussing fake bags.Online Communities

    Many digital communities and discussion boards are devoted to the topic of replica bags, where aficionados exchange tips, evaluations, and tips. Such websites offer useful insights & guidance for those exploring the imitation marketplace.In-Person Meetups

    Certain replica handbag enthusiasts organize in-person gatherings to showcase their own collections as well as talk about their passion for style. These meetings provide chances to network with similar people and exchange ideas.Influencers and Reviews

    Bloggers as well as influencers frequently evaluate replica handbags, providing genuine opinions as well as comparisons to authentic brand-name pieces. Following these evaluations could help one in making well-informed decisions about your buying.Legal and Ethical Considerations

    Comprehending the lawful along with moral facets regarding acquiring replica purses is essential for making well-informed selections. Here, we tackle some common issues.Intellectual Property Rights

    Imitation purses might infringe on the creative property assets of luxury brands. Be mindful of the legal consequences and potential hazards linked with buying and having imitations.Ethical Shopping

    Consider the ethical implications of endorsing the knockoff handbag industry. Although it offers cheap alternatives, it might also lead to exploitative labor conditions and ecological issues.Making Informed Choices

    Future Trends within Knockoff Purses

    The imitation handbag sector is continuously continually changing, featuring novel trends and innovations emerging. Here, we explore a few potential upcoming developments.

    Green ComponentsConclusion

    Given that environmental responsibility grows as a growing issue, the copy bag field may move towards using eco-friendly components. This transition might appeal to environmentally conscious consumers and decrease the sector’s eco-impact.

    Cutting-edge Tech

    Progress in innovation, for example additive manufacturing, may revolutionize the manufacturing of replica bags. These innovations may produce even better copies that are challenging to identify from the real ones.

    Evolving Consumer Attitudes

    Buyer views towards replica purses could continue to shift, with more embrace and recognition for superior imitations. This change could drive demand and influence field movements.

    Replica bags offer a stylish and affordable alternative for fashion enthusiasts and luxury lovers. By understanding the intricacies of the replica bag market, you can make informed choices and enjoy the benefits of high-quality imitations. Whether you’re drawn to the affordability, variety, or the ability to experiment with different styles, replica bags provide a gateway to the world of luxury fashion.

    Ready to explore the world of replica bags? Join our community of fashion enthusiasts and start your stylish journey today!

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

    Наши специалисты помогут вам разобраться во всех нюансах и ответят на все ваши вопросы. Мы обещаем, что процесс расчета стоимости станет для вас увлекательным и познавательным опытом. Ведь знание – это сила, особенно в мире ремонта и перепланировки!

  27. Приветствую. Может кто знает, где найти разные статьи о недвижимости? Сейчас читаю https://hameleon1.ru

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

發佈留言

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