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

66,327 Responses

  1. CharlesCep表示:

    Overview
    In a world that changes at rapid speed, the capacity to innovate isn’t just beneficial—it’s crucial. Whether you’re an entrepreneur, a corporate leader, or a coder, staying in the lead requires an creative mindset. This blog post will investigate the concept of innovation, uncovering what it takes to be a real innovator and why it’s more critical now than ever. You’ll learn qualities that define successful innovators, discover motivating case studies, and gain usable strategies for fostering your own creative thinking.
    What is Innovation and Why Does it Matter?
    Innovation is more than just a term; it’s the core of advancement. It involves creating new ideas or enhancing existing ones, leading to tangible benefits. In today’s quick environment, businesses must innovate to exist and prosper. Innovation drives effectiveness, enhances customer interaction, and opens new revenue streams. Without it, stagnation is certain.
    Traits of a True Innovator
    Creativity
    https://open.spotify.com/user/315dinldrfeteavaw5odm2f4cq6i
    At the center of innovation is creativity. This trait allows individuals to think beyond the limits the box, generating distinct solutions to complicated problems. Imaginative thinking can be cultivated by exposing oneself to diverse perspectives and backgrounds.
    Adaptability
    In a swiftly changing world, an innovator must be flexible. Being able to adjust when faced with new hurdles or opportunities is critical. Adaptability guarantees that you can progress alongside market trends and technological advancements.
    Risk-Taking
    Innovation often entails venturing into the uncertain. True innovators are willing to take thought-out risks. They know that failure is a part of the journey and use it as a learning tool to refine their ideas.
    Case Studies of Successful Innovators
    Elon Musk
    Elon Musk’s creative ventures, from Tesla to SpaceX, have transformed industries. His readiness to tackle huge technological challenges and shake up established markets showcases the power of a bold vision.
    Sara Blakely
    Sara Blakely, the entrepreneur of Spanx, turned a straightforward idea into a billion-dollar conglomerate. Her innovation in the fashion industry demonstrates how solving everyday problems can lead to remarkable success.
    Steve Jobs
    Steve Jobs’ unyielding pursuit of innovation transformed Apple into a international tech giant. His focus on design and user satisfaction set new criteria for the industry, proving that innovation can be a key differentiator.
    Fostering an Innovative Mindset
    Encourage a Culture of Openness
    Creating an atmosphere where new ideas are embraced and valued is paramount. Organizations should encourage employees to share their thoughts without fear of judgment. This openness fosters collaboration and sparks creativity.
    Learn from Failure
    Failure is an unavoidable part of the innovation path. Instead of dreading it, innovators should view failure as an opportunity to learn and grow. Analyzing what went wrong and why can provide valuable lessons for future efforts.
    Embrace New Technologies
    Technological advancements offer endless potential for innovation. Staying informed with the latest advancements and tools can provide a competitive edge. Whether it’s AI, blockchain, or IoT, leveraging new technologies can drive significant breakthroughs.
    The Role of Innovation in Business Growth
    Driving Efficiency
    Innovative methods can streamline operations, reducing costs and enhancing efficiency. Automation and digital transformation are instances of how businesses can innovate to enhance productivity.
    Enhancing Customer Experience
    Innovation can significantly improve customer satisfaction. By understanding customer requirements and developing tailored solutions, businesses can foster loyalty and promote growth. Tailored services and innovative products can set a company apart from its peers.
    Opening New Revenue Streams
    Innovative thinking can uncover new business opportunities. Diversifying product lines, entering new sectors, or developing unique services can open new revenue streams. This variety mitigates risk and promotes sustainable growth.
    Conclusion
    Innovation is the driving force behind success in today’s dynamic world. By understanding the qualities of true innovators, learning from effective case studies, and fostering an innovative mindset, you can unlock your creative potential. Remember, innovation isn’t just about revolutionary inventions; it’s about making continuous improvements that add value. Whether you’re leading a team or pursuing personal projects, the ability to innovate will set you apart and drive your success. Now, it’s time to put these insights into action and start your own original journey.

  2. JamesBuice表示:

    mexican drugstore online: buying from online mexican pharmacy – medicine in mexico pharmacies
    mexican mail order pharmacies

  3. Jamesruigo表示:

    https://mexicanpharma.icu/# buying prescription drugs in mexico online

  4. RobertWAisa表示:

    reliable canadian pharmacy reviews Online medication home delivery canadian king pharmacy

  5. Jamesruigo表示:

    https://indiadrugs.pro/# Online medicine order

  6. Trefyti表示:

    Приобретение диплома ПТУ с сокращенной программой обучения в Москве

    student-news.ru/kupit-diplom-nadezhnoe-reshenie-dlya-vashego-budushhego

  7. RobertWAisa表示:

    mexican rx online mexican pharma mexican mail order pharmacies

  8. Uazrchl表示:

    Быстрая схема покупки диплома старого образца: что важно знать?

    dip-ru.ru/gde-kupit-provedennii-diplom-tekhnikuma-v-2023-godu-bistro-i-nadezhno

  9. RobertWAisa表示:

    buying prescription drugs in mexico medication from mexico pharmacy mexican rx online

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

  11. Gartandabsex表示:

    Как поддерживать хорошее настроение с помощью смешных приколов

  12. DFW Roofing表示:

    Very good article! We are linking to this particularly great article on our website. Keep up the great writing.

  13. Gartandabsex表示:

    Как развеселить друга с помощью смешных приколов

  14. JamesBuice表示:

    medicine in mexico pharmacies: mexican pharma – mexico drug stores pharmacies
    medicine in mexico pharmacies

  15. Michaelphync表示:

    Introduction
    In a world that transforms at incredible speed, the capacity to innovate isn’t just helpful—it’s essential. Whether you’re an business owner, a business leader, or a coder, staying ahead requires an creative mindset. This blog post will investigate the notion of innovation, uncovering what it takes to be a true innovator and why it’s more significant now than ever. You’ll learn traits that distinguish successful innovators, uncover motivating case studies, and gain realistic strategies for fostering your own creative thinking.
    What is Innovation and Why Does it Matter?
    Innovation is more than just a buzzword; it’s the lifeblood of development. It entails creating new ideas or improving existing ones, leading to measurable benefits. In today’s fast-paced environment, businesses must innovate to exist and grow. Innovation propels effectiveness, enhances customer satisfaction, and opens new revenue streams. Without it, stagnation is unavoidable.
    Traits of a True Innovator
    Creativity
    https://www.twitch.tv/rileyreesepurdue
    At the core of innovation is creativity. This trait allows individuals to think beyond the limits the box, generating distinct solutions to complex problems. Creative thinking can be fostered by introducing oneself to diverse perspectives and experiences.
    Adaptability
    In a swiftly changing world, an innovator must be adaptable. Being able to change when faced with new hurdles or opportunities is critical. Adaptability assures that you can progress alongside market trends and technological advancements.
    Risk-Taking
    Innovation often involves venturing into the uncertain. True innovators are willing to take calculated risks. They understand that failure is a part of the process and use it as a growth tool to enhance their ideas.
    Case Studies of Successful Innovators
    Elon Musk
    Elon Musk’s creative ventures, from Tesla to SpaceX, have revolutionized industries. His readiness to tackle enormous technological challenges and disrupt established markets showcases the power of a bold vision.
    Sara Blakely
    Sara Blakely, the entrepreneur of Spanx, turned a simple idea into a billion-dollar conglomerate. Her innovation in the clothing industry demonstrates how solving everyday problems can lead to remarkable success.
    Steve Jobs
    Steve Jobs’ persistent pursuit of innovation transformed Apple into a worldwide tech giant. His focus on aesthetics and user satisfaction set new benchmarks for the industry, proving that innovation can be a key advantage.
    Fostering an Innovative Mindset
    Encourage a Culture of Openness
    Creating an environment where new ideas are accepted and valued is crucial. Organizations should promote employees to share their thoughts without fear of judgment. This openness fosters cooperation and sparks creativity.
    Learn from Failure
    Failure is an certain part of the innovation process. Instead of fearing it, innovators should view failure as an opportunity to learn and grow. Reviewing what went wrong and why can provide valuable understandings for future projects.
    Embrace New Technologies
    Tech advancements offer endless possibilities for innovation. Staying current with the latest trends and tools can provide a competitive edge. Whether it’s AI, blockchain, or IoT, leveraging new technologies can drive significant breakthroughs.
    The Role of Innovation in Business Growth
    Driving Efficiency
    Innovative processes can streamline operations, reducing costs and boosting efficiency. Automation and digital evolution are instances of how businesses can innovate to enhance productivity.
    Enhancing Customer Experience
    Innovation can significantly improve customer satisfaction. By understanding customer requirements and developing customized solutions, businesses can foster loyalty and promote growth. Personalized services and innovative products can set a company apart from its competitors.
    Opening New Revenue Streams
    Innovative thinking can uncover new commercial opportunities. Diversifying product lines, entering new sectors, or developing unique services can open new revenue streams. This variety mitigates risk and promotes sustainable growth.
    Conclusion
    Innovation is the driving force behind achievement in today’s ever-changing world. By understanding the traits of true innovators, learning from successful case studies, and fostering an innovative mindset, you can unlock your inventive potential. Remember, innovation isn’t just about groundbreaking inventions; it’s about making constant improvements that add value. Whether you’re leading a team or pursuing solo projects, the ability to innovate will set you apart and drive your success. Now, it’s time to put these insights into action and start your own innovative journey.

  16. Gartandabsex表示:

    Как поддерживать хорошее настроение с помощью забавных приколов

  17. Gartandabsex表示:

    Как развеселить друга с помощью забавных приколов

  18. WilliamDeeli表示:

    Здравствуйте!
    Мы можем предложить дипломы.
    forums.unigild.com/index.php?/topic/201107-купить-диплом-без-очередей-и-ожиданий

  19. Sazrakg表示:

    Сколько стоит диплом высшего и среднего образования и как его получить?
    zdshitula.ru/forum/?PAGENAME=message&FID=1&TID=233&MID=38808&result=new#message38808

  20. RobertWAisa表示:

    canadian pharmacy no scripts canadian pharmacy antibiotics onlinepharmaciescanada com

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

  22. RobertWAisa表示:

    canadapharmacyonline com Pharmacies in Canada that ship to the US buy canadian drugs

  23. ArthurReile表示:

    Фотофабрика кашеварных гарнитуров в течение Санкт-петербурге – этто ваш надежный участник на основании кашеварных интерьеров. Наша сестра работаем сверху разработке, производстве также аппарате первоклассных кухонных гарнитуров, коим сочетают на себе стиль, работоспособность и долговечность. Наша поручение – даровать покупателям отдельные вывода, организованные из учётом ихний пожеланий а также необходимостей, чтобы всякая кухня остановилась уютным и спокойным местом чтобы жизни и творчества http://tivokya0kuhnishki.ru.

發佈留言

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