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

121,063 Responses

  1. BradleyEdino表示:

    slot siteleri slot siteleri en kazancl? slot oyunlar?

  2. DavidTouts表示:

    https://sweetbonanza25.com/# sweet bonanza giris

  3. where can i get cheap co-amoxiclav without dr prescription buying cheap co-amoxiclav pills where can i buy generic co-amoxiclav prices
    can i order co-amoxiclav without a prescription can i get co-amoxiclav prices how to buy cheap co-amoxiclav without prescription
    where can i get generic co-amoxiclav prices
    cost of co-amoxiclav without prescription how to buy generic co-amoxiclav for sale where to buy cheap co-amoxiclav
    where can i buy cheap co-amoxiclav price can you buy co-amoxiclav price where to buy cheap co-amoxiclav for sale

  4. rubber stamp online maker [url=stamp-creator-online0.com]rubber stamp online maker[/url] .

  5. вызвать капельницу от запоя на дому [url=www.vyvod-iz-zapoya-rostov224.ru]вызвать капельницу от запоя на дому[/url] .

  6. вывод из запоя на дому недорого вывод из запоя на дому недорого .

  7. вывод из запоя на дому ростов недорого вывод из запоя на дому ростов недорого .

  8. вывод из запоя круглосуточно ростов-на-дону вывод из запоя круглосуточно ростов-на-дону .

  9. BradleyEdino表示:

    guvenilir casino siteleri bonus veren yasal bahis siteleri en guvenilir casino siteleri

  10. DavidTouts表示:

    https://slotsiteleri25.com/# slot siteleri

  11. выведение из запоя ростов на дону [url=http://vyvod-iz-zapoya-rostov224.ru]выведение из запоя ростов на дону[/url] .

  12. stamp maker online [url=http://stamp-creator-online0.com/]stamp maker online[/url] .

  13. вывод из запоя капельница на дому вывод из запоя капельница на дому .

  14. JacobLoody表示:

    https://vosf.ru — Переходите на сайт vosf, чтобы выбрать идеальную кухню.

  15. вывод из запоя круглосуточно ростов-на-дону [url=www.vyvod-iz-zapoya-rostov224.ru]вывод из запоя круглосуточно ростов-на-дону[/url] .

  16. FrankEmine表示:

    Casino Siteleri: en guvenilir casino siteleri – Casino Siteleri

  17. Wallacefex表示:

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

  18. Wilbertacild表示:

    Understanding Convex Finance
    Convex Finance is an innovative platform designed to enhance yield farming in the decentralized finance (DeFi) space. It allows users to maximize their rewards without the need for technical expertise.

    What is Convex Finance?
    Convex Finance is a DeFi platform that builds on top of , optimizing the way liquidity providers and stakers can earn rewards. By using Convex, users can increase the efficiency and profitability of their investments.
    convex finance
    Key Features of Convex Finance
    Enhanced Rewards: Users can earn boosted rewards on their staked assets by utilizing the Convex platform.
    Decentralized and Secure: Built on top of the existing Curve protocol, ensuring a high level of trust and security.
    User-Friendly Interface: Designed to be easy for both new and experienced DeFi users to navigate.
    Why Choose Convex Finance?
    There are several compelling reasons to choose Convex Finance for your yield farming needs. Whether you’re new to DeFi or an experienced investor, Convex offers unique benefits:

    Higher Yields: By pooling your resources, Convex helps maximize the potential returns on your investments.
    Gas Fee Efficiency: Transactions through Convex are optimized to reduce costs, making it a more efficient choice.
    Community-Driven: Convex evolves based on user feedback, ensuring that the platform continues to meet the needs of its community.
    Getting Started with Convex Finance
    Starting with Convex Finance is straightforward:

    Visit the .
    Connect your compatible crypto wallet.
    Select the pools you want to stake in and boost your earnings.
    For more detailed instructions, referring to the section will provide deeper insights and troubleshooting support.

    Conclusion
    Convex Finance revolutionizes the way users interact with DeFi, offering enhanced yields while maintaining a focus on security and simplicity. By leveraging the capabilities of Convex, investors can confidently optimize their yield farming strategies.

    Boost Your Earnings with Convex Finance Staking
    Are you looking to maximize your returns on cryptocurrency investments? Discover the potential of Convex Finance Staking today. This innovative platform offers you the opportunity to earn more by staking popular tokens like CRV, achieving enhanced yields while gaining additional benefits.

    What is Convex Finance?
    is a cutting-edge decentralized finance (DeFi) protocol that optimizes returns for Curve Finance users. It allows liquidity providers and CRV stakers to earn trading fees, boosted CRV, and take part in Convex liquidity mining.

    Why Choose Convex Staking?
    Here’s why Convex Finance should be your go-to platform for staking:

    Boosted Yields: Earn higher returns by leveraging your CRV tokens and engaging in liquidity mining.
    No Withdrawal Fees: Enjoy the flexibility to withdraw your funds without incurring additional costs.
    Rewards and Bonuses: Benefit from various incentives, including platform rewards and additional bonuses for loyal stakers.
    How to Start Staking on Convex Finance
    Follow these simple steps to start maximizing your crypto profits with Convex Finance:

    Connect Your Wallet: Use a compatible wallet like MetaMask to link your account to the platform.
    Stake Your CRV: Deposit your CRV tokens into Convex to start earning boosted rewards.
    Claim Your Rewards: Monitor your earnings and claim your rewards at your convenience.
    Explore More Benefits
    Aside from staking, Convex Finance offers a unique opportunity to participate in liquidity pools and yield farming initiatives. These options provide you with multiple avenues to enhance your total returns on investments.

    Start Staking Today
    Visit the official website to learn more about which pools and strategies offer the best returns. Take action today and secure your financial future with Convex Finance’s powerful staking solutions.

    Understanding Convex Finance: Boost Your DeFi Earnings
    As decentralized finance (DeFi) continues to grow, Convex Finance emerges as a powerful tool for users looking to optimize their Curve Finance (CRV) earnings. Whether you’re a seasoned crypto enthusiast or a newcomer, understanding how Convex Finance works can significantly enhance your income from DeFi investments.

    What is Convex Finance?
    Convex Finance is a platform that allows liquidity providers (LPs) and CRV stakers to earn higher returns without locking CRV. It achieves this by leveraging specific tokenomics to maximize yield earnings for users, while simplifying the staking process.

    How Convex Finance Works
    Here’s a breakdown of how Convex Finance operates:

    Increased Yield: Convex offers LPs additional rewards on top of the incentives already provided by Curve Finance. This maximizes your DeFi returns.
    Platform Flexibility: Unlike traditional staking, Convex Finance enables users to stake either LP tokens or CRVs without enduring long lock-up periods.
    Reward Distribution: Participants earn not just from Curve rewards but also receive a share of fees distributed by the platform, further increasing potential earnings.
    Benefits of Using Convex Finance
    There are several reasons to consider using Convex Finance:

    Efficient Yield Optimization: Convex Finance combines yields from multiple sources, providing a streamlined way for users to maximize their earnings.
    Lower Commitment: Users can earn rewards without the need for long lock-up periods, maintaining greater liquidity and flexibility.
    Community Support: With an active community and ongoing development, Convex Finance regularly updates its platform features to ensure high performance and security.
    Getting Started with Convex Finance
    To begin using Convex, you’ll need to connect a compatible crypto wallet and deposit your Curve LP tokens. Once connected, you can decide on the best strategy for your investment needs, benefiting from the enhanced yields available on this innovative DeFi platform.

    Overall, Convex Finance represents an evolving landscape in decentralized finance, offering a compelling option for maximizing CRV earnings with minimal staking constraints. Explore this platform to leverage its full potential and take advantage of the thriving DeFi ecosystem.

  19. online stamp design maker [url=https://stamp-creator-online0.com/]online stamp design maker[/url] .

  20. выезд на дом капельница от запоя [url=http://vyvod-iz-zapoya-rostov224.ru]выезд на дом капельница от запоя[/url] .

  21. stamp making online [url=www.stamp-creator-online0.com]stamp making online[/url] .

  22. LarryNem表示:

    Desyn Protocol
    The Desyn Protocol: An Overview
    The Desyn Protocol is a cutting-edge framework designed to enhance blockchain technology by offering a scalable and more secure ecosystem. As the demand for decentralized applications grows, the need for efficient protocols becomes crucial. Desyn addresses these needs with a unique approach, providing developers and organizations with the tools to build and manage decentralized systems with enhanced capabilities.
    desyn
    Core Features of Desyn Protocol
    Scalability: The protocol integrates advanced scalability solutions, allowing for increased transaction throughput and reduced latency.
    Security: By utilizing state-of-the-art cryptography, Desyn ensures that transactional integrity and data protection are maintained.
    Flexibility: Desyn’s modular architecture enables seamless adaptability to various use cases in the blockchain sector.
    Applications and Benefits
    The Desyn Protocol is versatile, finding applications across different sectors that require blockchain solutions. In finance, it aids in creating smart contracts that bring efficiency and transparency to financial transactions. In supply chain management, Desyn can enhance traceability and accountability from production to distribution. The healthcare industry benefits from secure, immutable record keeping, ensuring both data integrity and patient privacy.

    With its emphasis on scalability and security, Desyn reduces resource consumption while optimizing performance, thus driving down operational costs. The flexibility of its architecture supports rapid deployment and integration with existing systems, providing a strategic advantage to businesses looking to transform digitally.

    Moreover, developers benefit from the open-source nature of the protocol, which encourages community involvement and continuous innovation. Desyn’s approach promises to lower barriers to entry for startups and established companies alike, fostering a vibrant ecosystem of development.

    Conclusion
    In conclusion, the Desyn Protocol represents a significant advancement in blockchain technology by combining scalability, security, and flexibility. Its wide range of applications and benefits make it a preferred choice for various industries seeking to leverage blockchain’s transformative power. As the landscape of decentralized technology evolves, Desyn is poised to play a pivotal role, offering solutions that are innovative, efficient, and secure. The protocol’s commitment to enhancing user experience and enabling strategic growth makes it a valuable asset in the digital transformation journey.

  23. вывод из запоя дешево ростов на дону http://www.vyvod-iz-zapoya-rostov224.ru .

  24. вывод из запоя ростов и область [url=https://vyvod-iz-zapoya-rostov224.ru/]вывод из запоя ростов и область[/url] .

發佈留言

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