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,可能是一個活動網頁、公司形象網頁…等,也許就沒有必要去選用一個前端框架,簡言之工具用在正確的地方,才能顯現出它的價值,當然目前符合使用框架的專案也一定非常多,也就是這樣的原因,才會造成前端框架的流行。
mexican border pharmacies shipping to usa: mexico pharmacy – best mexican online pharmacies
best mexican online pharmacies: buying from online mexican pharmacy – mexican pharmaceuticals online
https://mexicanpharmacy1st.shop/# mexican pharmaceuticals online
medicine in mexico pharmacies п»їbest mexican online pharmacies mexican pharmaceuticals online
Жіночі тренди онлайн-журнал для стильних, модних та впевнених у собі представниць прекрасної статі. Любов, відносини, краса, здоров’я, кар’єра, діти, подорожі, рецепти – все це ви знайдете тут.
mexico drug stores pharmacies: mexican border pharmacies shipping to usa – mexican mail order pharmacies
https://mexicanpharmacy1st.online/# mexican mail order pharmacies
Путаны Москвы devkiru.com
Если Вы искали шлюхи метро домодедовская в Москве, то прямо сейчас заходите на указанный сайт. Мы предлагаем заказать самых недорогих проституток в Мск. Но в этом вопросе, низкая цена не означает качество. Просто у девочек в данной категории не так много практики, и принимают они в квартирах чуть дальше от центра Москвы и не очень фешенебельных. Не стоит волноваться, что невысокая цена может испортить Ваш досуг, точнее — наоборот. Вероятность великолепно провести досуг по хорошей цене-дважды приятнее.
mexican drugstore online: purple pharmacy mexico price list – reputable mexican pharmacies online
best online pharmacies in mexico: buying prescription drugs in mexico online – pharmacies in mexico that ship to usa
medicine in mexico pharmacies pharmacies in mexico that ship to usa best online pharmacies in mexico
Allnew Boss Dont delete Drastically reduced Exclusive deal
Get it now Get started now Important information regarding Instant Limited
time New customers only Now only Satisfied free 0 risk 00 1
month ago 18 18 video 31 50 off 100 free 100 more 100 satisfaction 100 satisfied AS SEEN ON Accept credit cards Acceptance Access
Access now Accordingly Act Act Immediately Act now Act now Dont hesitate Action Required Ad Additional income Addresses Addresses on CD Affordable All All natural All
new Allnatural Amazing Apply Online Apply now Apply online As As
seen on At no cost Auto email removal Avoice bankruptcy Avoid Avoid bankruptcy BUY BUY DIRECT Bargain Be amazed Be your own boss
Become a member Being a member Beneficiary Best price Big bucks
Bill 1618 Billing Billing address Billion Billion dollars Bonus Brand new pager Bulk email Buy Buy direct Buy now
Buying judgments CURES BALDNESS Cable converter Call Call free Call now Calling creditors Cancel Cancel at any time Cannot be combined with any other offer
Cant live without Card accepted Cards accepted Cash Cash bonus Cashcashcash Casino Celebrity Cellphone cancer scam
Cents on the dollar Certified Chance Cheap Cheap meds
Check Check or money order Claims Claims not to be selling anything Claims to be legal Claims you are a winner Clearance Click Click below Click here
Click here link Click to remove Click to remove mailto Collect Collect child support Compare Compare rates Compete for your business
Confidentiality Confidentially on all orders Congratulations Congratulations Consolidate
debt Consolidate debt and credit Consolidate your debt Copy DVDs Copy
accurately Cost Costs Credit Credit bureaus Credit card
offers Cures Cures baldness Cutie DIAGNOSTICS Deal Deal ending soon Dear emailfriendsomebody Dear personalization variable Dear email Dear friend Dear somebody Debt
Diet Different reply to Dig up dirt on friends Digital marketing Direct email Direct marketing Discount Discusses search
engine listings Do it now Do it today Dont delete Dont hesitate Dont hesitate Dormant Double your Double your cash Double your income Drastically reduced Earn Earn Earn cash Earn extra cash Earn money Earn per week Easy terms Ecommerce Eliminate bad
credit Eliminate debt Email harvest Email marketing Exclusive
deal Expect to earn Explode your business Extra Extra cash Extra income Free FAST Fantastic Fantastic deal Fast Viagra delivery Fast cash Fast money
Financial Financial freedom Financially independent Find out anything For Only For free For instant access For just some amount For just insert whatever amount For just XXX
For just xxx Form Free Free DVD Free access Free cell phone Free consultation Free gift Free grant money Free hosting Free info Free installation Free investment Free leads
Free membership Free money Free offer Free preview Free priority mail Free quote Free sample
Free trial Free website Freedom Friend Full refund Get Get
it away Get it now Get it today Get out of debt Get paid Get rid of debt Get
started now Gift certificate Give it away Giveaway Giving away Great offer Growth hormone Guarantee
Guaranteed Have you been turned down Hello Here Hidden Hidden assets Hidden charges Home Home Based business
Home based Home employment Homebased Homebased business Hot
babes Hottie Human Human growth hormone Hurry up If only it were that easy Important information regarding In accordance with laws Income Income from home
Increase Income Increase sales Increase traffic Increase your sales Incredible deal Info you requested
Information you requested Instant Instant weight loss Insurance Insurance Lose weight Internet market Internet marketing Investment Investment decision Its effective Join millions Join millions of
Americans Join thousands Junk Kinky Laser printer Leave Legal Life Life insurance Lifetime Limited time Limited time offer Limited time only Loan Loans Long distance phone offer Lose
Lose weight Lose weight spam Lottery Lower interest rate
Lower interest rates Lower monthly payment Lower rates Lower
your mortgage rate Lowest insurance rates Lowest price Luxury Luxury car
MLM Mail in order form Maintained Make Make money Marketing Marketing solution Marketing solutions Mass email Mature Medical Medicine Medium
Meet girls Meet singles Meet women Member Member stuff
Message contains Message contains disclaimer Million Million dollars Miracle Money Money back Money making Month trial
offer More Internet Traffic More internet traffic Mortgage Mortgage rates Multi level marketing Multilevel marketing Name brand Near you Never New New customers only New domain extensions Nigerian No age restrictions No
catch No claim forms No cost No credit check No disappointment No
experience No fees No gimmick No hidden No
hidden Costs No hidden costs No hidden fees No interest No inventory No investment No medical exams
No medical exams No middleman No obligation No purchase necessary No purchase required No questions asked No
refunds No selling No strings attached Noobligation Not intended Not junk Notspam Now Now only Obligation Off shore Offer
Offer expires Offers coupon Offers extra cash Offers free often stolen passwords Offshore
Once in a lifetime Once in lifetime One hundred percent
free One hundred percent guaranteed One time One time mailing Online biz opportunity Online biz opportunity Online business opportunity
Online degree Online marketing Online pharmacy Only Open Opportunity Opt in Order Order now Order
shipped by Order status Order today Orders shipped by Orders shipped by priority mail Orders shipped by shopper
Outstanding values Passwords Pennies a day People just leave money laying around
Performance Please read Potential earnings Preapproved Price Prices Print form signature Print out and fax Priority
mail Prize Prizes Problem Produced and sent out Profits Promise Promise you Promise
you Pure Profits Pure profit Quote Quotes Rates Real thing Refinance Refinance home
Refinanced home Removal Removal instructions Remove Remove in quotes
Remove subject Removes wrinkles Reply remove subject Request Requires initial investment Reserves the right Reverses Reverses
aging Risk free Riskfree Rolex Round the world S 1618
Safeguard notice Sale Sales Sample Satisfaction Satisfaction guaranteed Save Save big Save big
money Save up to Score Score with babes Search engine Search engine listings Search engines Section 301 See for
yourself Sent in compliance Serious cash Serious
only Sex Sexy babes Shopping spree Sign up free Sign up free today Social
security number Solution Spam Special promotion Stainless steel
Steamy Stock alert Stock disclaimer statement Stock pick Stop Stop snoring Stops
snoring Strong buy Stuff on sale Subject to cash Subject to credit Subject to Subscribe Success Supplies
are limited Take action Take action now Talks about hidden charges
Talks about prizes Teen Tells you its an ad Terms and conditions The best rates The following form They keep
your money no refund They keep your money no refund Theyre just giving it away This is an ad This isnt junk This isnt
spam This isnt a scam This isnt junk This isnt spam This wont last Thousands Trial US dollars
Undisclosed Undisclosed recipient University diplomas Unlimited Unsecured
credit Unsecured creditdebt Unsecured debt Unsolicited Unsubscribe Urgent VIAGRA DELIVERY Vacation Vacation offers
Valium Valium Viagra Very Cheap Viagra Viagra and other drugs Vicodin Visit our website Wants credit
card Warranty We are legal We hate spam We honor all Web traffic Weekend
getaway Weight loss What are you waiting for While stocks last While supplies last While you sleep Who really wins Why pay more
Will not believe your eyes Win Win big Winner Winning Won Work
at home Work from home XXX Xanax You are a winner You
are a winner You have been selected Your income Youve been selected adrianne animal arms bakire baldız buttocks cannabis child porn cocaine cp ecstasy erotic erotig erotik eskort etek gizli go url
growth hormone haydar hayvan heroin hidden charges hikaye homosexual hot
how to molest how to rape a man iptal itiraf ketamine kulot laurence sampson limited time liseli lsd mephedrone
nefes off partner penis enlargement surgery rebbeca
parer sarisin seen on seks sex sex toys sexual enhancers sexual fetish lingerie shawn mchugh sheila shopper
sicak snoring sperm telekz telekız vaginal laser rejuvenation viagra viagra satın al viagrayı çevrimiçi satın alın viagrayı çevrimiçi satın alındit
weight spam wilma melrose xxx yasak yerli yetiskin yetişkin videosu zoo çocuk pornosu
çocuk pornosudiz Hidden assets
cialis 2.5mg
https://mexicanpharmacy1st.shop/# best online pharmacies in mexico
medicine in mexico pharmacies mexico pharmacy mexican rx online
buy azithromycin 500mg online usa
buying prescription drugs in mexico online: buying from online mexican pharmacy – mexican rx online
cialis soft tabs pills stop – levitra soft lad viagra oral jelly online sack
buy valtrex in mexico
synthroid 37.5 mcg
mexican border pharmacies shipping to usa: п»їbest mexican online pharmacies – buying from online mexican pharmacy
https://mexicanpharmacy1st.online/# mexican border pharmacies shipping to usa
https://mexicanpharmacy1st.online/# buying prescription drugs in mexico online
заказать дипломную работу https://diplomworkmsk.ru/ с гарантией.
https://mexicanpharmacy1st.com/# buying from online mexican pharmacy
видеостена москва http://www.videosteny14.ru/ .
mexico pharmacies prescription drugs: reputable mexican pharmacies online – mexico drug stores pharmacies
http://mexicanpharmacy1st.com/# mexico pharmacy
cialis soft tabs pills hurt – cialis oral jelly pills sixty viagra oral jelly online meal
medicine in mexico pharmacies: mexico drug stores pharmacies – mexico pharmacies prescription drugs