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

124,769 Responses

  1. VernonPap表示:

    Say hello to Marinade Finance—the smarter way to stake on Solana! With Marinade staking, your Marinade SOL turns into Marinade Staked SOL, unlocking liquidity through Marinade mSOL. The platform is powered by the community via Marinade DAO and the MNDE token. Wondering about Marinade vs Lido? Users trust Marinade for its strong APY and proven Marinade Finance Audits. Start staking now at https://marinade.ink and grow your Solana securely!

  2. StevenDuase表示:

    indian pharmacy online shopping: indian pharmacy online – Medicine From India

  3. 1win_mwkr表示:

    прогнозы lucky jet прогнозы lucky jet .

  4. SheilaGot表示:

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

    Редметсплав.рф гарантирует все стадии сделки, предоставляя полный пакет необходимых документов для законного использования товаров. Неважно, какие объемы вам необходимы – от мелких партий до крупнооптовых заказов, мы готовы выполнить любой запрос с непревзойденным обслуживанием.

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

    Заходите на наш сайт Редметсплав.рф и убедитесь, что качество и уровень нашего сервиса – наилучшее решение для вашего бизнеса.
    Наши товары:

    Медный удлиненный двухраструбный отвод 90 градусов под пайку 76.1х65х1.6 мм 33.5х36.5 мм твердая пайка М3РМ ГОСТ Р 52922-2008 Покупайте медные двухраструбные отводы 90 градусов под пайку на Редметсплав.рф. Надежные и долговечные отводы из высококачественной меди для систем водоснабжения, отопления и кондиционирования воздуха. Гарантированно надежные соединения, простой монтаж и оптимальное распределение потока.

  5. Michaelrom表示:

    canadian online drugstore: Express Rx Canada – pharmacy in canada

  6. kypit 1s_bhsa表示:

    программа 1с цена программа 1с цена .

  7. kypit 1s_ivOi表示:

    сколько стоит программа 1с http://www.bisound.com/forum/showthread.php?p=1951167/ .

  8. MichaelLoapy表示:

    Medicine From India indian pharmacy online best online pharmacy india

  9. сухие силовые трансформаторы купить http://www.eisberg.forum24.ru/?1-0-0-00000333-000-0-0-1745397118 .

  10. StevenDuase表示:

    canadian discount pharmacy: Express Rx Canada – onlinecanadianpharmacy

  11. DennisSar表示:

    An interesting cryptocurrency tumbler is Ethereum. It supports bitcoin and Ethereum cryptocurrencies bearing no logs policy. It requires a minimum deposit of 0.2 BTC and the transaction fee is 2–5%. It does not support multiple addresses and requires 6 confirmations. No registration is required and it does not offer a referral program. Yomix : Zero-log policy Coin Mixer : Fast payouts Bitcoin Mixer : It offers flexible transaction fees and a low minimum transaction limit Mixero : Excellent customer support Bitcoin Laundry : Uses stealth pools to anonymize transactions 1. Yomix – Zero-log policy This particular Yomix supports Bitcoin cryptocurrency and does not bear any logs policy. It requires a minimum deposit of 0.01 BTC and the transaction fee is 1–3%. It supports multiple addresses of up to 10 and requires confirmation. No registration is required and it does offer a referral program.Yomix is being listed at the #1 spot here, well that’s not without substance. The top reasons why I’m in love with this Bitcoin tumbler is because it’s fast, takes care of our anonymity and privacy, and has a very negligible fee. Smartmix bitcoin mixing service The payout is almost instant, all it needs is 2 confirmations for the dirty coins being sent in to be cleaned or tumbled. No account needs to be created to clean your coins either. They have advanced options which let you set “delayed payouts” which further increase your anonymity and make it hard to link the coins going inside to the coins coming out. There’s even an option to add up to 5 addresses, so your coins are broken down into 5 different parts and sent to the different addresses again adding another layer of anonymity. The minimum amount too is pretty low being just 0.001BTC while the maximum limit is 15.32BTC. It’s pocket-friendly as well, with the fee being just 0.5% per mix + 0.0001BTC/address, in fact, it probably is one of the lowest fee in the industry altogether. As for anonymity, they delete all logs related to your mix after 7 days which finally erases the last thread which could ever be linked back to you. So yes, enough reasons to list it at the #1 spot, don’t you agree?Yomix is a Bitcoin mixer that processes Bitcoin and Bitcoin Cash transactions. The site offers a referral program for new users and supports multiple recipient addresses. Transaction fees start at 0.5% plus an extra 0.0001 BTC for each extra address added.Another trustworthy mixer is Yomix which supports two cryptocurrencies with Ethereum to be added soon. The mixing process is quite typical and similar to the processes on other tumblers. It is possible to set a time-delay option up to 72 hours and a sender has an opportunity to split the transaction, so the funds are sent to several addresses. Thus, sender’s funds are more secured and untraceable. Pros: Available in Tor Uses stealth pools to anonymize transactions 2. Coin Mixer – Fast payouts Coin Mixer is another one of the mixer that deserves to top most Bitcoin mixer charts based. For starters its user-interface is one of the simplest and easiest to understand. Then, it supports as many as 10 additional addresses, which is the maximum most mixers on this list support. Its fee based on address, 0.0002 per address, no service fee. It has a no logs policy with a 7-day default retention of the logs for support and transaction-related issues, although users get to permanently and instantly delete the logs manually whenever they wish anytime before this 7-day auto clear period as well. Does provide distribution control for each individual address separately; time-delay too is available although it’s randomly set by the platform and not user-controlled. The minimum limit too is quite low at just 0.0005BTC while the maximum limit depends on the real-time reserves. Bottom line, apart from lower user-control on fee and time-delays it’s pretty perfect.Straight off, Coin Mixer is the only Bitcoin Tumbler we’ve ever crossed paths with which offers a “Free trial”! The free trial obviously doesn’t mean they’ll just send you free money; rather no fee or commission is charged for this free trial although it’s limited to, and is exclusive for 0.0001BTC tumbling only. Their process of acquiring the clean coins is quite unique, obtained from various stock exchanges such as DigiFinex, Cryptonex, Binance and so on; ensuring cleaner coins than some other questionable sources pertaining to their claimed check using a proprietary algorithm. In the background, a user’s money is first mixed in their pre-mixer with other coins; then sent to the stock exchanges for further mixing with other traders’ coins and then summoned back to be sent back to the users. The major flaw with the tumbler however is its lack of user-control, users have absolutely no control over the time-delays meaning you can’t specify the duration gap between the outputs rather it’s randomized between 1-6 hours. Distribution-control too can’t be controlled and the mixer sends randomized outputs to the addresses. The fee can’t be controlled by the users either and is again randomly set between 4-5%+ 0.00015 BTC network fee, truth be told it’s one of the highest tumbler fee we’ve ever seen. The minimum deposit limit is 0.0001 BTC and the maximum being 50BTC/ transaction.Coin Mixer is unique in the sense that it offers support for both Bitcoin and Ethereum. The site does not require registration and has a minimum deposit requirement of 0.2 BTC. Transaction fees range from 2 – 5% depending on the amount that is being transferred. There is no referral program offer for Coin Mixer and multiple addresses are not supported. Finally, letters of guarantee are not provided.Coin Mixer is a btc shuffle service needed to hide your transfers in the bitcoin world. Coin Mixer currently has a minimum withdrawal threshold of 0.03500000 BTC, so users are advised to deposit more than the entry threshold plus commission, otherwise they will not be able to withdraw funds. The client is asked to set 5 exit addresses. If for some reason, even after a delay of two hours, the user’s balance is not updated, the mixer can contact the support service to take action. For customers who have been inactive for several days, it can take up to 15 minutes after logging in before you see outstanding deposits. Transaction histories are automatically deleted within 1 week after that. The program runs on a dedicated server that is openly connected via the Internet (you don’t need to do this when using the Tor browser). The Bitcoin mixer is launched on another machine, all suspicious activity is monitored, and the website is automatically protected in case of any indication that it is under DDoS attack. Pros: Customizable mixing settings for better anonymityIt offers flexible transaction fees and a low minimum transaction limit 3. Bitcoin Mixer – It offers flexible transaction fees and a low minimum transaction limitAn interesting cryptocurrency tumbler is Bitcoin Mixer. It supports bitcoin and Ethereum cryptocurrencies bearing no logs policy. It requires a minimum deposit of 0.2 BTC and the transaction fee is 2–5%. It does not support multiple addresses and requires 6 confirmations. No registration is required and it does not offer a referral program.Bitcoin Mixer offers a good number of features and has a no logs policy. To get started, you’ll need to deposit a minimum of 0.0015 BTC with no transaction fees charged. As an added plus, Bitcoin Mixer supports multiple addresses with a maximum of 5. You won’t have to register to use this service – which is great for those who prize their privacy. However, the site does not offer a referral program.Bitcoin Mixer supports Bitcoin and Litecoin cryptocurrencies bearing no logs policy. It requires a minimum deposit of 0.005 BTC, 0.015 LTC and the transaction fee is from 0.4% to 4% + mining fee 0.0003 for BTC, from 2% to 20% + mining fee 0.0003 for LTC. It supports multiple addresses of up to 5 and requires confirmation from 1 till 6. No registration is required and it does offer a referral program as well as a letter of guarantee.Bitcoin Mixer is one of its kind and requires special mention. It supports Bitcoin cryptocurrency and is clearly unknown on the point of no logs policy. It requires a deposit of at least 0.01 BTC and the transaction fee is 2% along with the 0.0004 BTC network fee. It supports multiple addresses of up to 10 and requires confirmation of 1. No registration is required and it does not offer a referral program. However, the letter of guarantee is provided. Pros: Zero-log policy Extensive FAQ section 4. Mixero – Excellent customer support Let’s take a look at another one of the leading bitcoin mixers which is incredibly easy to operate. Mixero has a straightforward interface and it is worth mentioning that the service fee is the lowest possible, it is 0.0% with 0.0002 BTC per extra address. Retention period is 7 days when it is easy for a user to manually remove all the logs which are saved for this period because of any future transaction-related problems. There is a time-delay feature, however, it is not possible to be controlled by a user but the mixing platform only.Mixero is one of its kind and requires special mention. It supports Bitcoin cryptocurrency and is clearly unknown on the point of no logs policy. It requires a deposit of at least 0.01 BTC and the transaction fee is 2% along with the 0.0004 BTC network fee. It supports multiple addresses of up to 10 and requires confirmation of 1. No registration is required and it does not offer a referral program. However, the letter of guarantee is provided.Mixero is a simple service that will increase your privacy while using and transacting Litecoin. Every single person have its right for a personal privacy even when transacting, trading or donating Litecoin. Due to litecoin blockchain features you are not completely anonymous while using LTC and here comes Litecoin Mixing Service to help you cut all ties between your old and fresh mixed LTC coins. Using LTC mixer makes almost impossible third-parties to trace your new Litecoin Address and find out how wealthy you are.Bitcoin Blender isn’t as heavily decorated as Mixero, as far as the webpage design goes. But the services and reviews are in no way less as compared to any of the top Bitcoin Tumbler services on the web. It’s a service functional since 2014, and offers two different kind of accounts: Quickmix: Requires no login, but offers lesser control Login enabled account: Requires you to login, provides for more control than the quickmix account. The mixing service is only accessible from its Onion URL, and even though it has a clearnet URL, it primarily only serves an educational purpose. It’s exclusively a Bitcoin mixing service, and supports only Bitcoin. As for the fee, it doesn’t have anything specific, and charges a random fee between 1-3%. This is done to keep our Bitcoins anonymous and more secure, rather than tagging them with a specific fee. Although there’s a special program, or incentive so to say, if amounts worth more than 10 BTC are deposited within a time-frame of 7 days, the fee is reduced by half! Obviously, there also is the time-delay feature, allowing us to delay the transaction by as much as 24 hours. As for security, it supports 2-factor authentication, facilitated with a customized PGP key which ensures only the holder of the PGP key along with the knowledge of the password can access your accounts. It also supports as many as 5 simultaneous deposit addresses, which get you the power to deposit unmixed funds by splitting them into more than one single transaction. And finally, there’s a no logs policy as well, and all the data including deposit addresses and support messages are deleted after 10 days. Pros: It has a positive reputation among the Bitcoin communitySecure Exchange 5. Bitcoin Laundry – Uses stealth pools to anonymize transactions Being honest, this isn’t the most feature-rich or control-rich Bitcoin Laundry mixer that’s available out there. However, it still averages mixes over 700Bitcoin/day (claimed, not verified). The coins are claimed to be sourced from mining pools in the U.S, China and Europe. Obviously they do not keep any logs. Unfortunately, only 1 output address is allowed which is a bit of a downer. The time-delay can fully be set manually. It can be as low as 0 hours, or as high as 48 hours. Any other delay between this frame can be set using the provided slider. The fee isn’t randomized, neither is it user-controlled. It’s set at a solid 0.1% for all transactions. Accepts a minimum Bitcoin deposit of 0.010BTC. Maximum funds which can be currently mixed stand at 677 BTC. Number of required confirmations depend on the amount. Only 1 is required for mixes below 2.5BTC. For 25 BTC it needs 3 confirmations. 4 confirmations for 40BTC and 5 confirmations for 50 BTC are required respectively. Doesn’t require registrations.Bitcoin Laundry is another simple yet trustworthy Bitcoin Tumbler service. And one of the primary differences it has compared to the other platforms on this list is that it can accommodate really “large volume transactions”. There is no maximum transaction limit as such, considering how their reserve is really huge and you’ll need to be a millionaire before you can run them out of funds. If any limit is breached, you are notified before you make the payment. The minimum transaction 0.001BTC, any amount lower than this is is considered a donation, like in the case of PriveCoin, and isn’t sent back to the customer. The minimum fee is 0.5%, with an additional 0.0005BTC for every deposited transaction. You can set a custom fee for added anonymity and they also provide a letter or guarantee like all the mentionable Bitcoin Tumblers out there.One of the most currency-rich mixers in the industry, letting us Mix not just Bitcoin but Litecoin, Bitcoin Cash and Ethereum (coming soon) is what Bitcoin Laundry is. Also flaunts probably the most colourful and easy to use Interfaces I’ve ever seen. Provides 100% Control to users regarding every aspect of the mix. As in, users control the exact amount of fee (to the 4th decimal point!), the exact time-delay (by the minute and not just hours) and also the Percentage distribution. It’s transparent and even has a “fee calculator” which displays the exact amount of funds a user would receive on each additional address, as well as the total service and the address-fee. Maximum 8 total output addresses allowed. The minimum service fee a user can pay is 1%, with the maximum being 5%. The additional address fee is 0.00045529 BTC, 0.01072904 LTC, and 0.00273174 BCH for Bitcoin, Litecoin and Bitcoin Cash respectively. Has three fund-pools, and they all have funds from different sources in them which have different levels of anonymity. Does have a “No Logs Policy”. No registration required.This platform can work not only as a toggle switch, but also as a swap, that is, you can clear your coins and change the cryptocurrency to another when withdrawing, which further increases anonymity. As a Bitcoin mixer, this platform provides the ability to set a custom commission: the higher the commission, the better the privacy. There is also a time delay option that increases the level of anonymity by delaying the transaction by 24 hours. The service has an impressive supply of coins, so your transactions are made instantly, as soon as confirmation of the receipt of coins arrives, unless you manually set time delays. The minimum deposit is 0.01 BTC per transaction. Any smaller amount is also accepted, but is considered a “donation” and is not returned to Bitcoin Laundry customers. Finally, they also have a no log policy. Pros: Excellent customer support Allows extra payout addresses

  12. Michaelrom表示:

    mexico pharmacy order online: mexico drug stores pharmacies – mexico pharmacies prescription drugs

  13. изготовление и установка лестниц в доме http://www.izgotovlenie-lestnic-na-zakaz.ru/ .

  14. mostbet_xiPi表示:

    mostbet.com казино скачать [url=mostbet8010.ru]mostbet.com казино скачать[/url] .

  15. Dannytal表示:

    mexico pharmacies prescription drugs: mexican online pharmacy – mexico pharmacies prescription drugs

  16. купить лестницу на заказ [url=http://www.izgotovlenie-lestnic-na-zakaz.ru]купить лестницу на заказ[/url] .

  17. StevenDuase表示:

    best canadian online pharmacy: Canadian pharmacy shipping to USA – reputable canadian pharmacy

  18. ZacharyRetry表示:

    производство металлических значков изготовление значков из металла

  19. WalterIcort表示:

    http://expressrxcanada.com/# buying from canadian pharmacies

  20. kypit 1s_wrOi表示:

    где купить 1с бухгалтерия где купить 1с бухгалтерия .

  21. kypit 1s_ciOi表示:

    купить программу 1с бухгалтерия https://www.wisdomtarot.tforums.org/viewtopic.php?f=15&t=22004 .

發佈留言

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