透過Vue實現限制數入字數

我們都知道,平常在社群網站上會限制使用者輸入的字數。最具代表性的網站就是Twitter,Twitter限制一般使用者每次發表文章的字數在140字以內。讓使用者用最簡短的文字來表達想法。對於優化使用者體驗比較好的方式是,當使用者在輸入的同時,提示使用者還有多少字可以輸入,當使用這輸入的字數達到限制時,及時地停止使用者繼續輸入。 像這樣子限制使用者輸入字數的機制要如何來實現呢? 有兩的點需要注意: 如何計算使用者輸入了多少字? 當使用這輸入的字數達到限制時,該如何停止繼續輸入? 今天我們就要透過Vue.js來製作一個可以幫我們控制輸入字數的程式。首先,我們先準備好需要的HTML檔案。 <!DOCTYPE html> <html lang=“zh-TW”> <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” /> <link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css” integrity=“sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO” crossorigin=“anonymous” /> <title>Start</title> </head> <body> <div id=“app” class=“container”> <div class=“row”> <div class=“col”> <textarea cols=“30”

使用 Vue.js -安裝與建立第一個應用程式

Vue是什麼?

依照官方說法
Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
Vue是一套用來構建使用者界面的漸進式(Progressive)框架。它只處理視圖的部分,特別的是,Vue被設計為可以由下而上漸進式的適用在網站上面。並且可以與其他各種元件庫並存。Vue也完全能夠為複雜的單頁網站應用提供支援。你可以一步一步階段性的來使用,不必一開始就使用所有的部分。

Vue在設計上使用MVVM(Model-View-ViewModel)模式。當View產生變化時,會自動更新到ViewModel。反之,當Model產生變化時,也會自動更新到ViewModel。View和Model之間則透過資料的雙向綁定(data-binding)建立連結。MVVM模式讓Vue可以將視圖與資料拆分開來,並且分離,你可以只關心資料就好了。


安裝Vue安裝Vue的方法,有下面幾種:

檔案安裝

首先您需要到Vue的網站下載檔案:vuejs.org
它的位置在guide/insatllation裡面。
你可以看到有兩個版本可以使用:

  • Development Version(建議在學習時使用這個版本)
  • Production Version

CDN安裝

透過CDN安裝的話,只要將下面這行加入你的HTML頁面裏。
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

NPM安裝

官網建議較大型的專案可以採用這種安裝方式。
$ npm install vue

命令列工具CLI安裝

這是另一種安裝方式,主要是為單頁面應用快速搭建(SPA)繁雜的鷹架。

建立第一個Vue應用程式

學習每個程式都是從Hello World應用開始。下面我們來看看這個資料雙向綁定的Vue程式。

透過 v-model,進行雙向綁定vue 中的 text。所以,當input裡面的內容變更時,data裡面的text也會跟著改變。


<input type="text" v-model="text">
<script>
        var VM = new Vue({
            el: '#app',
            data: {
                text: 'Hello World',
            }
        })
    </script>



留言

這個網誌中的熱門文章

用Python的條件實現電影分級流程

Vue元件實作,將HTML網頁Vue元件化

Python基礎篇--[條件]如果發生這種狀況時,我該怎麼辦?