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

79,910 Responses

  1. JacobLoody表示:

    http://vizitnews.ru/ — Простота заказа кухни через удобный интерфейс сайта vizitnews.

  2. Franknex表示:

    обмен криптовалюты 2024 – ferma cc официальный сайт, Быстрый обмен криптовалют

  3. DeweyTup表示:

    Renzo Protocol: Secure Blockchain Innovation
    Discover the Renzo Protocol: Revolutionizing Blockchain
    The Renzo Protocol represents a significant advancement in the blockchain technology landscape. It offers a secure and efficient platform for decentralized applications, setting a new standard in the industry.
    renzo ezeth
    Key Features of the Renzo Protocol
    The Renzo Protocol is designed to enhance the functionality and security of blockchain applications. Here are some of its key features:

    High Security: Utilizing advanced encryption methods to protect user data and transactions.
    Scalability: Capable of handling a large number of transactions per second, making it ideal for various applications.
    Decentralization: Ensures that no central authority controls the network, maintaining the core principles of blockchain.
    Interoperability: Seamlessly connects with other blockchain networks and systems.
    Benefits for Developers and Businesses
    The Renzo Protocol offers numerous benefits for both developers and businesses looking to leverage blockchain technology:

    Reduced Costs: By automating processes and cutting out intermediaries, businesses can significantly reduce operational costs.
    Improved Transparency: Every transaction is recorded on the blockchain, providing an immutable and transparent ledger.
    Enhanced Trust: The secure nature of the protocol builds trust among users and stakeholders.
    Development Support: Provides extensive documentation and tools to help developers create robust applications.
    Getting Started with the Renzo Protocol
    To start utilizing the Renzo Protocol, follow these simple steps:

    Visit the Renzo Protocol website and create an account.
    Access the API documentation and development tools.
    Join the Renzo community to connect with other developers and experts.
    Start building and deploying your decentralized applications.
    The Renzo Protocol is not only a beacon of security and efficiency in the blockchain space but also a catalyst for innovation. Whether you are a developer, a business leader, or simply interested in cutting-edge technology, the Renzo Protocol offers the tools and community support needed to drive your projects to success. Embrace the future with the Renzo Protocol and harness the full potential of blockchain technology.

    Renzo Protocol Restaking Guide
    Renzo Protocol Restaking: A Comprehensive Guide
    Renzo Protocol has revolutionized the method through which investors can maximize their crypto assets, particularly through the innovative concept of restaking. This guide will explore the benefits, processes, and strategies of restaking within the Renzo Protocol ecosystem, helping you make the most out of your investments.

  4. FrankEmine表示:

    en kazancl? slot oyunlar?: slot oyunlar? puf noktalar? – slot casino siteleri

  5. CharlesArelf表示:

    Welcome to Karak: Pioneering Blockchain Solutions
    The world of blockchain is evolving rapidly, and Karak is at the forefront of this revolution. Whether you are a developer, an investor, or merely a tech enthusiast, Karak offers a unique blend of innovative solutions designed to meet the diverse needs of the blockchain community.
    karak network
    What is Karak?
    is a sophisticated blockchain platform engineered to provide cutting-edge solutions that streamline processes and enhance efficiency. With a focus on decentralization, security, and speed, Karak integrates seamlessly with existing technologies to deliver a scalable blockchain experience.

    Key Features of Karak
    One of the standout aspects of Karak is its comprehensive suite of features aimed at solving complex blockchain issues.

    Scalability: Karak’s architecture is designed to handle a high volume of transactions without compromising performance.
    Security: Robust security protocols ensure the integrity and confidentiality of data across all network points.
    Interoperability: Seamlessly integrates with various blockchain networks, fostering collaboration and innovation.
    User-Friendly Interface: Intuitive design that caters to both professionals and novices in the blockchain space.
    Why Choose Karak?
    Choosing Karak is choosing a future-proof solution. Its dedicated team of developers and blockchain experts continually work to enhance the platform, ensuring it meets the present and future demands of its users.

    The benefits of using Karak include:

    Access to a rapidly growing ecosystem that supports a vast array of applications.
    A commitment to transparency and community-driven development.
    Dynamic support systems that help users navigate and maximize platform capabilities.
    Get Started with Karak
    Jump into the world of digital transformation with Karak today. Visit to explore the platform and stay ahead in the dynamic blockchain landscape.

    For more information, updates, and support, sign up for the Karak newsletter and become a part of the innovation that is reshaping the future of blockchain.

  6. Bruceder表示:

    Maximize Your Crypto Trading with ParaSwap
    If you’re looking to enhance your cryptocurrency trading experience, it’s time to explore ParaSwap. This innovative platform serves as a decentralized exchange aggregator, giving you the best deals on the market.
    para swap
    What is ParaSwap?
    ParaSwap is a cutting-edge platform that aggregates the best prices from various decentralized exchanges. It provides users with the most efficient path to execute their trades by considering factors like price impact and gas fees.

    How Does ParaSwap Work?
    ParaSwap functions by connecting directly to multiple liquidity sources. It then simplifies the process of trading across different platforms by bringing the best rates to users all in one place. This means that you don’t have to hop between multiple exchanges—you can find everything you need through ParaSwap.

    Benefits of Using ParaSwap
    Competitive Rates: ParaSwap offers some of the best rates by aggregating prices from various platforms.
    Efficiency: Trade execution is designed to be quick and reliable.
    Transparency: Get clear insights into your trades with detailed transaction information.
    Why Choose ParaSwap?
    Choosing ParaSwap means straightforward, efficient crypto trading. Whether you’re a seasoned trader or new to the crypto space, having a tool like ParaSwap can enhance your trading strategy by ensuring you’re always accessing the best available prices.

    Getting Started
    To start trading with ParaSwap, simply connect your crypto wallet, input the details of your trade, and let ParaSwap find the best route for your transaction. It’s that simple!

    Conclusion
    Maximize your trading potential by leveraging the power of ParaSwap. With its aggregated approach to finding the best prices, efficiency, and transparency, ParaSwap stands out as a leading choice for cryptocurrency traders.

  7. JasonUnsoG表示:

    http://sweetbonanza25.com/# sweet bonanza slot

  8. FrankEmine表示:

    deneme bonusu veren siteler yeni: deneme bonusu veren siteler – yeni deneme bonusu veren siteler

  9. Wallacefex表示:

    denemebonusuverensiteler25: deneme bonusu veren yeni siteler – deneme bonusu veren yeni siteler

  10. RobertGot表示:

    Crypto Funk https://besttodaynew.com is a fresh look at cryptocurrencies. News, trends, guides and analytics for beginners and professionals. Find out how to get the most out of blockchain technology!

  11. BradleyEdino表示:

    deneme bonusu veren casino siteleri canl? casino siteleri rcasino

  12. вывод из запоя на дому в екатеринбурге вывод из запоя на дому в екатеринбурге .

  13. Wallacefex表示:

    denemebonusuverensiteler25: deneme bonusu veren yeni siteler – deneme bonusu veren yeni siteler

  14. Wallacefex表示:

    sweet bonanza oyna: sweet bonanza – sweet bonanza kazanma saatleri

  15. вывод из запоя капельница [url=www.vyvod-iz-zapoya-ekaterinburg25.ru/]вывод из запоя капельница [/url] .

  16. FrankEmine表示:

    guvenilir casino siteleri: guvenilir casino siteleri – canl? casino siteleri

  17. FrancisGetty表示:

    Federal Gov Open Enrollment https://body-balance.online is your chance to upgrade or choose an insurance plan. Easy navigation, expert support, and a wide range of programs will help you make the right choice. Apply now!

  18. Orvilleced表示:

    guvenilir slot siteleri: en cok kazand?ran slot oyunlar? – en cok kazand?ran slot oyunlar?
    tl casino

  19. выведение из запоя [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]выведение из запоя[/url] .

  20. вывод из запоя [url=vyvod-iz-zapoya-ekaterinburg27.ru]вывод из запоя[/url] .

  21. FrankEmine表示:

    denemebonusuverensiteler25: yat?r?ms?z deneme bonusu veren siteler – deneme bonusu veren siteler yeni

發佈留言

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