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

117,801 Responses

  1. WalterIcort表示:

    https://expressrxcanada.shop/# canadian pharmacy no scripts

  2. mostbet_bapn表示:

    войти в мостбет https://mostbet8006.ru .

  3. Антистресс игрушки для улучшения настроения.
    Антистрес играчки цени http://www.antistres-igrachki.com/ .

  4. Kukli_yaei表示:

    Истории успеха: дети, полюбившие куклы бебета.
    Истински кукли бебета http://kukli-bebeta.com/ .

  5. 1win_kmpr表示:

    portofele electronice casino https://1win5054.ru/ .

  6. Timastus表示:

    платформа для покупки аккаунтов маркетплейс аккаунтов

  7. HaroldBlown表示:

    Manuala metode
    Manuala FUE procedura tiek izmantots tikai roku darbs, graftus atdalot ar instrumentu, kura diametrs ir 0.9-1.00 mm. Parstadits tiek viss grafts, kas parasti satur 1-4 matu folikulus, nedalot atseviski pa 1 graftam, tadejadi iegustot kuplu un dabigu rezultatu.
    Aesthetica
    Dr. Ilze Runce veicot griezienus, strada ar mikroskopu, kas dod iespeju iegut matu biezumu, kas maksimali pietuvinats dabigajam un viena procedura iespejams parstadit lidz pat 4000 graftu. Manuala FUE metode tiek izmantota ari uzacu un bardas parstadisana. Procedura norit vieteja anestezija un ir klientam komfortabla – tas laika pacients visu laiku atrodas sedus stavokli proceduru kresla un var lietot datoru, telefonu, planseti, lasit gramatu vai skatities TV.

    Dr. Ilze Runce ir manualas metodes aizsaceja Latvija, ir atseviski apguvusi so metodi Kazahstana 1 gada garuma pie nozares profesionaliem un ieviesusi to Latvija kops 2013.gada, kopuma ir veikusi jau vairak ka 1000 manualas FUE proceduras.

    Aprakstu sagatavoja Dr. Ilze Runce

    Manualas metodes cena ieklauts viss nepieciesamais:
    nepieciesamais graftu daudzums;
    visi pecoperacijas medikamenti;
    sprejs;
    sampuns;
    cepurite;
    pusdienas proceduras diena;
    parsiesana nakamaja diena (pec nepieciesamibas).
    MATU IZKRISANA

    Pastiprinata matu izkrisana jeb alopecija skar gan viriesus, gan sievietes. Ta var but saistita ar novecosanos, genetiku, hroniskam slimibam, ieilgusu stresu, ka ari specifiskam imunas sistemas reakcijam. Mati klust plani vai pilniba izkrit. Ari retas un apdegumi zonas, kur agrak ir bijis apmatojums, (piemeram, uzacis) var radit estetisku diskomfortu.

    Matu parstadisanas procedura ir efektivs risinajums gadijumos, kad medikamenti un arstnieciskas proceduras nepalidz!

  8. Josephwed表示:

    How it works: it has its own cryptocurrency reserve, which can be represented as a chain of bitcoins. When you transfer your funds to the Blender io, the resource sends your funds to the end of the chain and sends you new coins from the beginning of the chain that have nothing to do with the old coins. therefore, there can be no connection between incoming and outgoing coins. Only coins that go from your wallet to the Unijoin address can be tracked through the public ledger, but no further. Blender io does not require you to register or provide any information other than the “receiving address“! It does not require identity confirmation and registration, but it is mandatory to provide in addition to the “receiving address”. The additional withdrawal delay feature has been extended to the maximum and offers installation up to 24 times a day. Other servers do not have such a wide range of latencies. Each set of unrefined coins can be split into as many as 8 pieces and sent to different addresses with an additional fee of 0.00008 BTC per address. Yomix : It offers flexible transaction fees and a low minimum transaction limit Coinmize : Zero-log policy Coin Mixer : Fast payouts Bitcoin Laundry : Uses stealth pools to anonymize transactions Mixero : Excellent customer support 1. Yomix – It offers flexible transaction fees and a low minimum transaction limitIf you’re looking for a mixer which neither keeps any logs, nor asks you to register; Yomix is an option you can peek at. It does offer registrations in case you’d want to keep things professional, organized and are a frequent mixer. It’s one of the very few mixers which offer “multiple deposit addresses” (upto 5); so you can break the deposit into multiple parts which add upto your total amount. Even offers 2-FA (via PGP) for account security. It also acts as a BTC aXMR a BTC convertor which further adds anonymity. The fee is randomized between a minimum 1% and a maximum 4%. Minimum Withdrawal and deposit limits are acceptable, currently 0.00045 BTC and 0.0018 BTC respectively. Upto 10 additional addresses supported for each output. Time-delays aren’t completely user-controlled, yet users get to specify the maximum delay they want for the total output. All outputs are processed before this timer is reached. Instant withdrawal too available.Yomix 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.Yomix is a Bitcoin cleaner, tumbler, shifter, mixer and a lot more. It has a completely different working principal than most other mixers on this list. So, it has two different reserves of coins, one for Bitcoin and the other for Monero. It cleans coins by converting them to the other Cryptocurrency. So, you can either clean your Bitcoins and receive Monero in return, or vice-versa. The interface is pretty straight-forward. You simply choose your input and output coins, and enter your output address. For now, only 1 output address is supported which we believe simplifies things. The fee is fixed which further makes it easier to use. You either pay 0.0002 BTC when converting BTC to XMR, or 0.03442 XMR when converting XMR to BTC. It also provides a secret key which can be used to check transaction status, or get in touch with support. The process doesn’t take long either, Yomix only demands 1 confirmation before processing the mixes. Bitcoin amounts as low as 0003BTC and XMR as low as 0.05 can be mixed. It doesn’t require any registrations so obviously there’s no KYC. The company seems to hate the govt. and has a strict no-log policy as well.Compared to other Bitcoin tumblers, Yomix stands out from the crowd thanks to the additional anonymity offered. Users are given the option to split and merge coins into different wallets to various addresses. Additionally, Yomix provides support for unlimited addresses and does not require user registration. Although only Bitcoin is supported and there are no referral programs, ChipMixer does not charge users with any service fees. With the option to donate BTCs being made available. Pros: Excellent customer support User-controlled time delays 2. Coinmize – Zero-log policy Coinmize currently only supports Bitcoin mixes, however, it has plans to bring in ETH mixes in the near future. It has been featured on Bitcoin.com/ News BTC/ Crypto News/ The Next Web etc. hence building a bit of trust. Very modern, advanced, user-controlled interface. Allows upto 5 output addresses. Obviously, doesn’t keep any logs whatsoever. The user-control is impressive. You get to control the fund-distribution, as well as the time-delay for each output address manually. Even the fee can be set manually. The cheapest allowed fee is 0.5% which is more than acceptable. The highest is set at 5%. Obviously the 0.25mBTC blockchain transaction fee is attached on top of the selected fee. It even has a “strength meter” which shows how strong your mix is, based on all the factors you’ve selected. No registration required whatsoever. And it does provide the mixing code to ensure all outputs are fresh and not linked to any of your previous deposits.How it works: unlike other mixers, this site cleans coins with bitcoins purchased by them on cryptocurrency exchanges. Coinmize io examines purchased coins using a scoring system with innovative algorithms and the use of technologies such as blockchain volume analysis, cluster analysis, pollution analysis, etc. After that, you will receive your BTC back, divided into random parts, and even sent in different addresses, if necessary. The whole process takes about 6 hours. The mixer does not require registration and does not store any logs. After each mixing operation, a letter of guarantee is sent, and information about it is eliminated after 24 hours, ensuring complete anonymity. The service also provides round-the-clock technical support. MixTum io charges a flat fee of 5% of the transaction, as well as a network fee of 0.00015 BTC. The program has two versions – for regular browsers and Tor.And last but not least, there is a coin mixer with a number of cryptocurrencies to tumbler named Coinmize. At the moment, there are three currencies and Ethereum is going to be represented in future. This mixer offers a very simple user-interface, as well as the opportunity to have control over all steps of the mixing process. A user can select a delay not just by hours, but by the minute which is very useful. The tumbler gives the opportunity to use a calculator to understand the amount of money a user finally receives. The service fee is from 1 % to 5 % with fees for extra addresses (0.00045529 BTC, 0.01072904 LTC, and 0.00273174 BCH). Having funds from different resources helps the crypto mixer to keep user’s personal information undiscovered. This last mixer does not offer its users a Letter of Guarantee.Let’s take a look at another one of the leading bitcoin mixers which is incredibly easy to operate. Coinmize 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. Pros: It offers flexible transaction fees and a low minimum transaction limitAllows extra payout addresses 3. 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.Being honest, this isn’t the most feature-rich or control-rich Coin Mixer 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.Two cryptocurrencies are also supported on Coin Mixer mixing service. This scrambler is listed because it works quickly and it is reliable. The transaction fee is really low, only the amount of 0.0001 BTC needs to be sent for every extra address. Splitting deposited coins between 5 addresses is also extremely helpful for keeping user’s anonymity. Every user is able to choose an additional option of delaying the payment meaning that the transaction is becoming even more anonymous.Coin Mixer offers a unique service with a high degree of confidentiality, which will ensure the anonymity of your payments, by using the mixing of multiple Bitcoin addresses. Our system works quickly, reliably and with a small commission – only after the transfer and receipt of funds to the final address. Of course, all of the data about your transaction will be irretrievably deleted. Pros: Excellent customer support Proven track record 4. Bitcoin Laundry – Uses stealth pools to anonymize transactions Two cryptocurrencies are also supported on Bitcoin Laundry mixing service. This scrambler is listed because it works quickly and it is reliable. The transaction fee is really low, only the amount of 0.0001 BTC needs to be sent for every extra address. Splitting deposited coins between 5 addresses is also extremely helpful for keeping user’s anonymity. Every user is able to choose an additional option of delaying the payment meaning that the transaction is becoming even more anonymous.This is by far the most unique Bitcoin Laundry I’ve ever encountered till date; that’s so pertaining to its “Time-travel” feature! (Whoa!) Basically instead of operating on the traditional receive unclean coins > send clean coins process, it instead uses a create wallet > fund it with chips beforehand > receive unclean coins > grant access to the pre-funded wallet process! This lets users spend the clean coins even before the unclean coins were sent to the mixer (because the wallet was pre-funded) and that’s the reason I termed it the time-travel mixer. Also it funds the wallets with “chips” which are not the same thing as Bitcoins, they’re basically the private keys which can be exported to your Bitcoin wallets to fund your wallets with the amount the chips were worth. It also lets users bet their Chips which has a chance of doubling the worth of their chips, other advanced features include merging which lets users combine two big chips into one single chip, or splitting which divides one big chip into two smaller chips. Its fee structure too is an unique- “Pay what you like” feature, which not only adds to user anonymity by randomizing the fee but also makes the service more affordable and customizable. Because users completely control when or how much funds they wish to withdraw, it translates into 100% user control on time-delays and distribution control. No logs are kept after a 7-day retention period; or there also is an option to manually scrub all logs whenever you wish prior to this 7-day period. The minimum deposit limit on the platform is 0.0001BTC.Bitcoin Laundry is one of the best Bitcoin Tumbler services, that I’m stating based on my personal experiences and the positive reviews of other users on the Internet. It works both as a Bitcoin Tumbler, as well as a swapper, meaning you can clean your coins, and receive them in a different cryptocurrency as well which further adds to their anonymity. As a Bitcoin Tumbler, they let you set a custom service fee, the higher this fee is, the better your coins are anonymized. There’s a time-delay option as well which let’s you add an extra layer of protection by delaying your transaction by up to 24 hours, so you receive your coins not instantly but at a later time set by you. As of now, it supports the following coins: Bitcoin Ethereum Bitcoin Cash Litecoin The minimum fee of mixing coins for Bitcoin is 0.8% + 0.0008BTC / forwarding address. Note that there is a minimum transaction limit of 0.01BTC/transaction, and anything below that limit is still accepted but considered “donations” and hence isn’t returned to the senders. As for confirmation, it needs 1 confirmation before it cleans your Bitcoins. And the time needed for the whole process is generally instant, except when you’ve manually specified a time-delay. Also, obviously there also is a “Guarantee certificate” which helps you resolve any future conflicts and issues. It also features a “no logs policy” like all the other Bitcoin Tumbler services on this list, and automatically deletes your order history and all the other data after 24 hours. Well, this is just one of the many available Bitcoin Tumbler services, so let’s head over to the other available options.An interesting cryptocurrency tumbler is Bitcoin Laundry. 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. Pros: It offers flexible transaction fees and a low minimum transaction limitExcellent customer support 5. Mixero – Excellent customer support Mixero has a Bitcoin reserve of its own, consider it a chain of Bitcoins, when you send your BTC to Blender.io it sends your coins to the end of the chain and sends you fresh, new, unlinked coins from the beginning of the chain. Hence there’s no link between the coins going in, and the coins coming out. Hence the public ledger would only be able to track the coins going from your wallet to the address of Blender.io but no further. Blender.io doesn’t require you to signup, register, or provide any kind of detail except the “receiving address”! That’s the only thing it needs, there can’t be a better form of anonymity if you ask me. Since you provide no personal details, there’s no way your identity can be compromised. Nor can it be linked back to you, since Mixero doesn’t know who you are. Blender.io is one of the most accommodating tumblers in this sense as well, most other tumblers offer 3-4 sets of delays, Blender.io offers as many as 24, yes one for each hour. It also lets you add as many as 8 new addresses for each transaction (most other tumblers allow no more than 5 addresses).Mixero is another one that requires consideration. It supports Bitcoin cryptocurrency bearing no logs policy. It requires a minimum deposit of 0.001 BTC and the transaction fee is 4–5%. It supports multiple addresses of 2 or custom options and requires confirmation. No registration is required and it does not offer a referral program. Letter of guarantee is offered.Mixero 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.Mixero 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 Mixero and multiple addresses are not supported. Finally, letters of guarantee are not provided. Pros: 24/7 customer support Extensive FAQ section

  9. 1win - Towly表示:

    Live-ставки: Множество матчей онлайн с быстрой реакцией
    В пространстве ставок на спорт одним из ключевых элементов является изменчивость и способность адаптироваться в моментально. 1win официальный сайт вход даёт шанс десятки тысяч спортивных событий, доступных в формате ставок в режиме реального времени. Мы предлагаем ставки к ведущим событиям мирового масштаба, будь то киберспорт.

    Лайв-ставки дают шанс учитывать динамику событий, что делает процесс более захватывающим, но и стратегически насыщенным. С применением аналитических ресурсов платформы, любители ставок могут делать ставки с уверенностью, увеличивая потенциальные результаты. Каждое событие содержит анализ игры, что помогает игрокам выбирать тактику исходя из фактов.

  10. ZacharyRetry表示:

    значок металлический с надписью http://metallicheskie-znachki-zakaz.ru

  11. MichaelLoapy表示:

    mexico pharmacy order online mexico pharmacies prescription drugs mexican online pharmacy

  12. MichaelLoapy表示:

    canadian pharmacy online ExpressRxCanada reliable canadian pharmacy

發佈留言

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