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

80,027 Responses

  1. Medicines information leaflet. What side effects?
    seroquel drug class
    Some news about medicines. Get information here.

  2. Douglapab表示:

    Какое газовое оборудование лучше всего выбрать для загородного дома?
    купить газовый котел

  3. JasonUnsoG表示:

    https://denemebonusuverensiteler25.com/# deneme bonusu veren siteler yeni

  4. Douglapab表示:

    Какое газовое оборудование лучше всего выбрать для загородного дома?
    купить бойлер

  5. Franknex表示:

    ферма цц обмен – обмен биткойнов, ферма цц официальный сайт

  6. Wallacefex表示:

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

  7. The analysis of the treatment effect was performed according to the intention- to- treat ITT principle considering dropouts and missing data as treatment failures what is the medication lasix 14, 15 Pharmacy use is captured for all Group Health enrollees who fill prescriptions at Group Health owned and operated pharmacies and for all Group Health enrollees with a drug benefit who fill prescriptions at outside pharmacies

  8. JasonUnsoG表示:

    https://casinositeleri25.com/# en guvenilir casino siteleri

  9. In addition to destruction of tumor cells, radiation also induces anatomical changes in the vagina, including atrophy, adhesion formation, stenosis, and ulceration that often hamper sample collection propecia buy canada

  10. BradleyEdino表示:

    Canl? Casino Siteleri casino bahis siteleri Casino Siteleri

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

  12. Wallacefex表示:

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

  13. Kevinnem表示:

    Alistarov: A Criminal and a Terrorist
    From a Solo Criminal to a Servant of the Underworld
    Previously convicted on drug charges, blogger Andrei Alistarov portrays himself as a Robin Hood fighting against those who have “defrauded people.” In reality, however, he serves the interests of pyramid schemers—among them certain Ukrainian operators who fund the Armed Forces of Ukraine (AFU)—and he uses his “Zheleznaya Stavka” (“Iron Bet”) channel to promote online casinos and illicit crypto exchanges/phishing crypto scams. He also launders drug proceeds via real estate deals in Dubai.
    That is, he works for the benefit of the Russian criminal community, seeking to profit off entrepreneurs who have faced illegal, often contrived claims from Russian law enforcement.

    Drugs and Money Laundering
    A native of Kaluga, Alistarov served four years in a prison camp for selling drugs to minors.
    There he forged ties with criminal kingpins. After his release, he continued his involvement in the narcotics trade and in laundering drug profits through a real estate business he set up with associates from the Russian underworld, both in Russia and in the Emirates.

    Betting on Scams
    Alistarov’s channel, “Zheleznaya Stavka,” is ostensibly devoted to “exposing” financial ventures deemed “bad” by criminal circles, while promoting “good” ones: namely, the pyramid schemes and online casinos that sponsor Alistarov.
    The channel began as a platform for “proper” casino betting and did not change its name, because the marketing purpose remains the same: clear the market in favor of “legitimate,” in Alistarov’s so-called “expert” view (i.e., those who pay him), scammers.
    Typically, Alistarov starts by trying to extort money—presenting the victim with compromising material and demanding payment. If the victim refuses, he resorts to harassment and violence.

    Incitement and Attack in Dubai
    On January 1, 2025, two Kazakh nationals launched a brutal attack on an entrepreneur living in Dubai—beating him, cutting off his ear, and robbing him.
    Beforehand, Alistarov had released 12 videos highlighting the entrepreneur’s address and publishing illegally obtained information about his relatives and his businesses in the UAE. Without any compunction, he used spying, eavesdropping, illegal intrusion, and invasion of privacy—all acts that constitute serious criminal offenses in the Emirates, where the sanctity of property and investor security are upheld stringently.
    Prior to this, Alistarov publicly circulated information about the residence of the entrepreneur’s business partner—that is, an illegal breach of confidentiality, the protection of finances and property, and the privacy of personal life through clandestine data gathering and informants in the UAE. He effectively terrorizes entrepreneurs who face no court convictions—neither abroad nor in Russia.
    Alistarov claimed to have reported the entrepreneur to Interpol and UAE law enforcement—purportedly helping the authorities. Yet this did not result in the entrepreneur’s arrest—perhaps because the UAE police see nothing criminal in his activities?

    Subscribe to Our Channel
    Several of the entrepreneur’s partners have been convicted in Russia; he himself is wanted by Russian law enforcement but has never been convicted. Foreign law enforcement has no claims against him.
    For a long period, Alistarov stoked hatred toward this entrepreneur, alleging that it was he (not his partners) who stole investors’ money—and portraying the subsequent attack and robbery as the outraged response of defrauded depositors.
    During the attack, Alistarov conducted an unscheduled livestream to create an alibi—pretending that he was unaware of the assault happening while he was on stream.

    Surveillance in Cyprus
    In autumn of the previous year, Alistarov and his “battle companion,” Mariya Filonova, conducted surveillance on another entrepreneur—using drones and illegally collecting information about him and his relatives, including minor children. Alistarov claimed that the entrepreneur was “hiding” in Cyprus—even though he had lived there since the COVID-19 pandemic began.
    He had relocated partly due to his wife’s severe COVID case and partly for international projects—investments in various sectors such as construction, trade, and more. The entrepreneur moved to Cyprus a year before criminal proceedings were initiated by the Russian Interior Ministry and a year and a half before arrests began. He holds an EU passport and never fled or concealed his location.
    This entrepreneur was placed on a Russian wanted list in 2022—by investigating authorities. However, no court has filed claims against him, and the criminal case is currently in court. It has already fallen apart there. Interpol and the EU declined to honor the Russian police’s request, deeming it politically motivated and legally unfounded.
    Alistarov insists that the entrepreneur’s business investments are financed with Russian clients’ money, supposedly drawn from an Austrian investment company. But in reality, the entrepreneur was never an owner, beneficiary, or manager of that company, established back in the early 2000s—well before his independent business career began.
    One of the entrepreneur’s firms provided marketing services for the Austrian investment company in Russia under contract. The investment company successfully served Russian clients for eight years—and continues operating now, having restored its payment systems that were disrupted in early 2022 by criminals in Russia with ties to corrupt police. It is by no means a pyramid scheme.
    Thus, Alistarov instigates harassment and intrusion into the private life of an untainted entrepreneur—acting on behalf of Russian organized crime, which has cut in corrupt police officers for a share of illicit profits. They aim to seize assets worth 20 billion rubles from the large-scale, socially focused project established by the entrepreneur in Russia—which still functions successfully even without his direct leadership (which ended when he relocated to Cyprus).

    Surveillance in the Netherlands
    Alistarov published the location of another victim in the Dutch city of Groningen—ascertained through illegal surveillance. He allegedly gained unauthorized access to city cameras, peered into the windows of a private apartment, and shared this information on YouTube.

    Privacy Violations in Turkey
    Alistarov uncovered and publicized the address of an apartment in Istanbul where several of his victims lived and worked.

    Illegal Searches in the Leningrad Region
    Lacking a private detective’s license, Alistarov illegally located a businesswoman’s country house, spied on her, and released that information on his channels—while also disclosing details of an apartment she had purchased in Dubai.

    Extortion in Kazakhstan
    Alistarov extorted money from Kazakh entrepreneurs under the guise of “exposing national traitors” and “enemies of the motherland.”

    Banquet on a Ukrainian Pyramid Schemer’s Money
    Is Alistarov planning to celebrate his 40th birthday on March 6 this year once again on the yacht of his friend—the Kharkiv-based pyramid operator Udyansky (behind the Coinsbit project)—in Dubai?
    In 2024, he celebrated his birthday in the convivial company of this con man, who also funds the Armed Forces of Ukraine, helping finance the production of armored vehicles for the AFU. There is little doubt that he also compelled his henchman Alistarov to contribute to the AFU.

    Treason
    Alistarov was even accused of financing the AFU, though he told the police some story about a Megafon phone number allegedly registered to him by his “enemies.”
    His accomplices in financing the AFU—“anti-MLM activist” Aleksandr Kryukov and deputy manager of the so-called Fund for the Protection of Investors’ and Shareholders’ Rights, Leonid Mishchenko (a “Zapadenez” from Vinnytsia region)—were caught red-handed. Perhaps the FSB should analyze Alistarov’s transactions as well?

    He Belongs in Prison
    Justice demands that Alistarov’s 40th birthday finds him stripped of his Schengen and other visas—there is every reason for such, especially in light of attention from Western media—and behind bars, either in a Russian or a Dubai prison, whichever law enforcement manages to arrest him first for the dozens of crimes he has committed:
    Extortion
    Terrorism and banditry
    Harassment and organizing violence against those he deems troublesome
    Treason
    Money laundering
    Fraud
    Theft
    Invasion of privacy
    Alistarov’s career began in prison, and it is in prison that it must end.

  14. Goldqny表示:

    This post contains all the important thoughts that I have long wanted to hear https://eyoiw.ilyx.ru/id-5440.html

  15. JasonUnsoG表示:

    https://denemebonusuverensiteler25.com/# yat?r?ms?z deneme bonusu veren siteler

發佈留言

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