1. 程式人生 > 其它 >Vue基礎語法

Vue基礎語法

學前準備

vue官網:https://cn.vuejs.org/

工具: webstorm, vscode

Vue基礎

初體驗

<div id="app">{{message}}</div>

<script>
    // 宣告式程式設計
    const app = new Vue({
        //用於掛載要管理的元素
        el: '#app',
        // 定義資料
        data: {
            message: '你好, 李銀河!'
        }
    })
</script>

效果

你好, 李銀河!

列表展示

<body>
    <div id="app">
        <ul>
            <li v-for="item in movies">{{item}}</li>
        </ul>
    </div>

    <script>
        const app = new Vue({
            el: '#app',
            data:{
                message: "電影名單",
                movies:['星際穿越', '大話西遊', '少年派', '盜夢空間']
            }
        })
    </script>
</body>

效果展示

瀏覽器追加資料

app.movies.push('海王')

小案例:計數器

<div id="app">
    <h2>當前計數:{{counter}}</h2>
    <button @click="add">+</button>
    <button @click="sub">-</button>
</div>

<script>
    const app = new Vue({
        el: '#app',
        data:{
            counter:0
        },
        methods:{
            add: function () {
                this.counter++
            },
            sub:function () {

                if(this.counter <= 0){
                    this.counter = 0;
                }else if(this.counter>0){
                    this.counter--;
                }

            }
        }
    })
</script>

實現效果

mvvm思想

mvvm簡介

MVVMModel–view–viewmodel)是一種軟體架構模式

MVVM有助於將圖形使用者介面的開發與業務邏輯後端邏輯(資料模型)的開發分離開來,這是通過置標語言或GUI程式碼實現的。MVVM的檢視模型是一個值轉換器,[1] 這意味著檢視模型負責從模型中暴露(轉換)資料物件,以便輕鬆管理和呈現物件。在這方面,檢視模型比檢視做得更多,並且處理大部分檢視的顯示邏輯。[1] 檢視模型可以實現中介者模式,組織對檢視所支援的用例集的後端邏輯的訪問。

MVVM是馬丁·福勒的PM(Presentation Model)設計模式的變體。[2][3] MVVM以相同的方式抽象出檢視的狀態和行為,[3] 但PM以依賴於特定使用者介面平臺的方式抽象出檢視(建立了檢視模型)。
MVVM和PM都來自MVC模式。

MVVM由微軟架構師Ken Cooper和Ted Peters開發,通過利用WPF(微軟.NET圖形系統)和Silverlight(WPF的網際網路應用派生品)的特性來簡化使用者介面的事件驅動程式設計。[3] 微軟的WPF和Silverlight架構師之一John Gossman於2005年在他的部落格上發表了MVVM。

MVVM也被稱為model-view-binder,特別是在不涉及.NET平臺的實現中。ZK(Java寫的一個Web應用框架)和KnockoutJS(一個JavaScript)使用model-view-binder。[3][4][5]

MVVM模式的組成部分

  • 模型

    模型是指代表真實狀態內容的領域模型(面向物件),或指代表內容的資料訪問層(以資料為中心)。

  • 檢視

    就像在MVCMVP模式中一樣,檢視是使用者在螢幕上看到的結構、佈局和外觀(UI)。[6]

  • 檢視模型

    檢視模型是暴露公共屬性和命令的檢視的抽象。MVVM沒有MVC模式的控制器,也沒有MVP模式的presenter,有的是一個繫結器。在檢視模型中,繫結器在檢視和資料繫結器之間進行通訊。[7]

  • 繫結器

    宣告性資料和命令繫結隱含在MVVM模式中。在Microsoft解決方案堆中,繫結器是一種名為XAML標記語言。[8] 繫結器使開發人員免於被迫編寫樣板式邏輯來同步檢視模型和檢視。在微軟的堆之外實現時,宣告性資料繫結技術的出現是實現該模式的一個關鍵因素。[4][9]

理論基礎

MVVM旨在利用WPF中的資料繫結函式,通過從檢視層中幾乎刪除所有GUI程式碼(程式碼隱藏),更好地促進檢視層開發與模式其餘部分的分離。[10] 不需要使用者體驗(UX)開發人員編寫GUI程式碼,他們可以使用框架標記語言(如XAML),並建立到應用程式開發人員編寫和維護的檢視模型的資料繫結。角色的分離使得互動設計師可以專注於使用者體驗需求,而不是對業務邏輯進行程式設計。這樣,應用程式的層次可以在多個工作流中進行開發以提高生產力。即使一個開發人員在整個程式碼庫上工作,檢視與模型的適當分離也會更加高效,因為基於終端使用者反饋,使用者介面通常在開發週期中經常發生變化,而且處於開發週期後期。

MVVM模式試圖獲得MVC提供的功能性開發分離的兩個優點,同時利用資料繫結的優勢和通過繫結資料的框架儘可能接近純應用程式模型。[10][11][12] 它使用繫結器、檢視模型和任何業務層的資料檢查功能來驗證傳入的資料。結果是模型和框架驅動儘可能多的操作,消除或最小化直接操縱檢視的應用程式邏輯(如程式碼隱藏)。

MVVM模式不同於MVC,在MVVM模式中,將ViewModel層繫結到View層後,它基本不使用點選事件,而是使用命令(Command)來控制。資料的顯示也是不同於MVC,而是使用Binding來繫結相關資料。

值得一提的是,MVVM通常會使用屬性更改通知,即資料驅動而不是事件驅動。在WPF中當資料發生改變時,會通過介面INotifyPropertyChanged通知到對應的元件繫結的資料,實現同步資料重新整理。

MVVM簡述

View層:

  • 檢視層
  • 在我們前端開發中,通常就是DOM層。
  • 主要的作用是給使用者展示各種資訊。

Model層:

  • 資料層
  • 資料可能是我們固定的死資料,更多的是來自我們伺服器,從網路上請求下來的資料。
  • 在我們計數器的案例中,就是後面抽取出來的obj,當然,裡面的資料可能沒有這麼簡單。

VueModel層:

  • 檢視模型層
  • 檢視模型層是View和Model溝通的橋樑。
  • 一方面它實現了Data Binding,也就是資料繫結,將Model的改變實時的反應到View中
  • 另一方面它實現了DOM Listener,也就是DOM監聽,當DOM發生一些事件(點選、滾動、touch等)時,可以監聽到,並在需要的情況下改變對應的Data。

vue基礎語法

v-once

  • 該指令之後不需要跟任何表示式
  • 該指令表示元素和元件直渲染一次,不會隨著資料的改變而改變

示例

<body>
<div id="app">
    <h2>{{message}}</h2>
    <h2 v-once>{{message}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '你好'
        }
    })
</script>
</body>

效果

v-html

  • 改指令往往會跟上一個string型別
  • 將string的html解析出來並進行渲染

例項

<div id="app">
    <h2>{{url}}</h2>
    <h2 v-html="url"></h2>
</div>


<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '',
            url: "<a href=\"https://cn.bing.com/?mkt=zh-cn\">必應</a>"
        }
    })

</script>

效果

繫結屬性:v-bind

<div id="app">
<!--    繫結屬性-->
    <img :src="imageURL" alt="">
    <a :href="aHref">1234</a>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '',
            imageURL:'https://cn.vuejs.org/images/logo.svg?_sw-precache=346e12ee28bb0e5f5600d47beb4c7a47',
            aHref:'https://www.cnblogs.com/',
        }
    })
</script>

v-bind繫結class

<head>
    <meta charset="UTF-8">
    <title>v-bind繫結class</title>
    <style>
        .active{
            color: red;
        }
    </style>
</head>
<body>
<div id="app">
    <h2 :class="active">{{message}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: 'v-bind繫結class',
            active: 'active',

        }
    })
</script>
效果
小案例: 利用button按鈕切換class
<head>
    <meta charset="UTF-8">
    <title>v-bind繫結class</title>
    <style>
        .active{
            color: red;
        }
    </style>
</head>
<body>
<div id="app">

    <h2 :class="{active: active, line:isLine}">{{message}}</h2>
    <button @click="btnClick">切換</button>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: 'v-bind繫結class',
            active: true,
            isLine:true,
        },
        methods:{
            // 狀態切換
            btnClick: function () {
                this.active = !this.active
            }
        }
    })
</script>
點選切換按鈕前
點選切換按鈕後

v-bind繫結style

物件語法
<div id="app">
    <h2 :style = "{fontSize: finalSize + 'px', backgroundColor: finalColor}">{{message}}</h2>
    <h2 :style = "getStyles()">{{message}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: 'Hello',
            finalSize: 100,
            finalColor: 'red',
        },
        methods:{
            getStyles: function () {
                return {fontSize: this.finalSize+ 'px', backgroundColor: this.finalColor}
            }
        }
    })
</script>
陣列語法
<div id="app">
    <h2 :style="[baseStyle, baseStyle1]">{{message}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: 'Hello',
            baseStyle:{backgroundColor: 'red'},
            baseStyle1:{fontsize: '100px'}
        }
    })
</script>

計算屬性

示例

<div id="app">
    <h2>{{fullName}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '',
            firstName:'Lebron',
            lastName: 'James'
        },
        //計算機屬性
        computed:{
            fullName: function () {
                return this.firstName + ' '+ this.lastName
            }
        }
    })
</script>

效果:

複雜些的

<div id="app">
    <h2>總價格:{{totalPrice}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            books:[
                {id:110, name: 'Unix程式設計藝術', price:119},
                {id:111, name: '程式碼大全', price:105},
                {id:112, name: '深入理解計算機原理', price:98},
                {id:113, name: '現代作業系統', price:87},
            ]
        },
        computed:{
            totalPrice: function () {
                let result = 0;
                for(let i=0; i<this.books.length;i++){
                    result += this.books[i].price
                }
                return result
            }
        }
    })
</script>

效果

get與set屬性

通常情況下, 計算屬性中沒有set,方法,預設只有get方法,即只讀

<!--本質上屬性中的方法都是屬性,所以不需要新增圓括號-->
<div id="app">{{fullName}}</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            firstName: 'Kobe',
            lastName: 'Bryant'
        },
        // computed完整寫法
        computed:{
            fullName:{
                set: function (newValue) {
                    const names = newValue.split(' ');
                    this.firstName = names[0];
                    this.lastName = names[1];
                },
                get: function () {
                    return this.firstName+ ' '+ this.lastName
                }
            }
        }
    })
</script>

計算屬性與methods對比

1.如果一個業務流程沒有返回值,則用methods實現,有返回值,用computed和methods都可以實現

2.計算屬性和方法都是函式,計算屬性一定有返回值,它通過對資料進行處理,返回一個結果

3.在模板中呼叫時,計算屬性不加(),而methods必須需要加()

4.計算屬性和方法最主要的區別是計算屬性有快取功能。
方法被呼叫時每次都要重複執行函式
計算屬性初次呼叫時執行函式,然後會快取結果。當再次被呼叫時,如果依賴的響應式資料沒有發生改變,則直接返回之前快取的結果 。如果依賴發生了改變,則會再次執行函式並快取結果

v-on

語法糖

v-on:click="sub"
// 語法糖
@click="sub"

v-on修飾符

Vue提供了修飾符來幫助我們方便的處理一些事件:

  • .stop - 呼叫 event.stopPropagation()。
  • .prevent - 呼叫 event.preventDefault()。
  • .{keyCode | keyAlias} - 只當事件是從特定鍵觸發時才觸發回撥。
  • .native - 監聽元件根元素的原生事件。
  • .once - 只觸發一次回撥。

vue條件判斷

<div id="app">{{result}}</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            score: '59'
        },
        computed:{
            result(){
                let result = '';
                if(this.score < 60){
                    result = '不及格'
                }else if(this.score>=60 && this.score<85){
                    result = '合格'
                }else{
                    result = '優秀'
                }

                return result
            }
        }
    })
</script>

小案例

使用者點選按鈕,進行登陸操作的切換

<body>
<div id="app">
    <span v-if="isUser">
        <label for="username">使用者賬號</label>
        <input type="text" id="username" placeholder="使用者賬號" key="usename">
    </span>

    <span v-else>
        <label for="email">使用者郵箱</label>
        <input type="text" id="email" placeholder="使用者郵箱" key="email">
    </span>

    <button @click="isUser = !isUser">切換型別</button>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            isUser: true
        }
    })
</script>
</body>

切換

v-show

<div id="app" >
        <button @click="toggle">切換顯示狀態</button>
        <h2 v-show="show">顯示</h2>
    </div>


<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            show: true
        },
        methods: {
            toggle() {
                this.show = !this.show
            }
        }
    })
</script>

效果

v-if與v-show的對比

  • v-if和v-show都可以決定一個元素是否渲染,那麼開發中我們如何選擇呢?
  • v-if當條件為false時,壓根不會有對應的元素在DOM中。
  • v-show當條件為false時,僅僅是將元素的display屬性設定為none而已。

開發中如何選擇呢?

  • 當需要在顯示與隱藏之間切片很頻繁時,使用v-show
  • 當只有一次切換時,通過使用v-if

迴圈(v-for)

v-for遍歷陣列

不使用下標值

<div id="app">
<!--在遍歷的過程中,沒有使用索引值(下標值)-->
        <ul>
            <li v-for="item in names">{{item}}</li>
        </ul>
    </div>

    <script src="../js/vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data:{
                names:['why', 'kobe', 'james', 'curry']
            }
        })
    </script>

效果:

使用下標值

<!--在遍歷的過程中,獲取索引值-->
        <ul>
            <li v-for="(item, index) in names">
                {{index+1}}.{{item}}
            </li>
        </ul>
    </div>

    <script src="../js/vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data:{
                names:['why', 'kobe', 'james', 'curry']
            }
        })
    </script>

效果

v-for遍歷物件

只獲取value

<div id="app">
    <!--在遍歷物件的過程中,如果只是獲取一個值, 那麼獲取到的是value-->
    <ul>
        <li v-for="item in info">{{item}}</li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            info: {
                name: 'why',
                age: 18,
                height: 1.88
            }
        }
    })
</script>

效果

獲取鍵值對

<div id="app">
    <!--在遍歷物件的過程中,如果只是獲取一個值, 那麼獲取到的是value-->
<!--    <ul>-->
<!--        <li v-for="item in info">{{item}}</li>-->
<!--    </ul>-->
    <!--獲取鍵值對-->
    <ul>
        <!--在vue中value在前-->
        <li v-for="(value, key) in info">{{value}}-{{key}}</li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            info: {
                name: 'why',
                age: 18,
                height: 1.88
            }
        }
    })
</script>

效果

獲取鍵值對和索引

<div id="app">
    <!--獲取鍵值對和索引-->
    <ul>
        <li v-for="(value, key, index) in info">{{value}}-{{key}}-{{index}}</li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            info: {
                name: 'why',
                age: 18,
                height: 1.88
            }
        }
    })
</script>

效果

新增key屬性

<div id="app">
    <ul>
    	<!--在迴圈時,key屬性中的值,應與要顯示的值相一致-->
        <li v-for="item in letters" :key="item">{{item}}</li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            letters: ['A', 'B', 'C', 'D', 'E']
        }
    })
</script>

小案例

需求: 在頁面中顯示列表內容,並伴隨點選使對應的選項變紅

<head>
    <meta charset="UTF-8">
    <title>05-作業的回顧和完成</title>
    <style>
        .active{
            color: red;
        }
    </style>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="(item, index) in movies"
            :class="{active: currentIndex === index}"
            @click="liClick(index)">
            {{index}}.{{item}}
        </li>
    </ul>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            movies:['海王', '海賊王', '加勒比海盜', '海爾兄弟'],
            currentIndex: 0
        },
        methods:{
            liClick(index){
                this.currentIndex = index
            }
        }
    })
</script>

效果

購物車案例

詳見資料中購物車案例文件

效果

完整程式碼

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>購物車</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- HTML5 shim 和 Respond.js 是為了讓 IE8 支援 HTML5 元素和媒體查詢(media queries)功能 -->
    <!-- 警告:通過 file:// 協議(就是直接將 html 頁面拖拽到瀏覽器中)訪問頁面時 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div id="app" v-if="books.length">
    <table class="table table-bordered text-center">
        <thead>
            <tr>
                <th></th>
                <th class="text-center">書籍名稱</th>
                <th class="text-center">出版日期</th>
                <th class="text-center">價格</th>
                <th class="text-center">購買數量</th>
                <th class="text-center">操作</th>
            </tr>
        </thead>

        <tbody>
            <tr v-for="(item, index) in books">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.date}}</td>
                <td>{{item.price}}</td>

                <td>
                    <!--當數量為1時,不允許點選-->
                    <button class="btn btn-default btn-sm" @click="sub(index)" :disabled="item.count<=1">-</button>
                    {{item.count}}
                    <button class="btn btn-default btn-sm" @click="add(index)">+</button>
                </td>

                <td>
                    <button class="btn btn-primary btn-sm" @click="remove(index)">移除</button>
                </td>


            </tr>
        </tbody>
    </table>

    <h2>總價格: {{totalPrice | showPrice}}</h2>
    <h2 v-else>購物車為空</h2>
</div>


<script src="../js/vue.js"></script>
<script src="main.js"></script>

<!-- jQuery (Bootstrap 的所有 JavaScript 外掛都依賴 jQuery,所以必須放在前邊) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<!-- 載入 Bootstrap 的所有 JavaScript 外掛。你也可以根據需要只加載單個外掛。 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</body>
</html>
const app = new Vue({
    el: '#app',
    data:{
        books: [
            {
                id: 1,
                name: '《演算法導論》',
                date: '2006-9',
                price: 85.00,
                count: 1
            },
            {
                id: 2,
                name: '《UNIX程式設計藝術》',
                date: '2006-2',
                price: 59.00,
                count: 1
            },
            {
                id: 3,
                name: '《程式設計珠璣》',
                date: '2008-10',
                price: 39.00,
                count: 1
            },
            {
                id: 4,
                name: '《程式碼大全》',
                date: '2006-3',
                price: 128.00,
                count: 1
            },
        ]
    },
    methods:{
        // 點選移除按鈕移除對應的行
        remove(index){
            this.books.splice(index, 1)
        },
        // 增加數量
        add(index){
            this.books[index].count++
        },
        // 縮減數量
        sub(index){
            this.books[index].count--
        },
    },
    computed:{
        // 計算全部價格
        totalPrice(){
            let totalPrice = 0;
            for(let i=0; i<this.books.length; i++){
                totalPrice += this.books[i].price*this.books[i].count
            }
            return totalPrice
        }
    },
    filters: {
        showPrice(price) {
            return '¥' + price.toFixed(2)
        }
    }
});

v-model

基本使用

<div id="app">
    <input type="text" v-model="message">
    {{message}}
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: 'Hello'
        }
    })
</script>

效果

文字效果隨著輸入框的內容改變,並與輸入框內容保持一致

v-model結合raido使用

<div id="app">
    <label for="male">
        <input type="radio" v-model="sex" id="male" value="男">男
    </label>

    <label for="female">
        <input type="radio" v-model="sex" id="female" value="女">女
    </label>
    <h2>您選擇的性別是:{{sex}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            sex: '男'
        }
    })
</script>

效果

v-model結合checkbox

模擬同意協議(單選)

<div id="app">
    <label for="agree">
        <input type="checkbox" id="agree" v-model="isAgree">
    </label>
    <h2>是否同意:{{status}}</h2>
    <button :disabled="!isAgree">下一步</button>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            isAgree: false
        },
        computed:{
            status(){
                let status = ''
                if (this.isAgree === false){
                    status = '不同意'
                }else{
                    status = '同意'
                }
                return status
            }
        }
    })
</script>
效果

多選

<div id="app">
<!--多選-->
    <input type="checkbox" v-model="hobbies" value="羽毛球">羽毛球
    <input type="checkbox" v-model="hobbies" value="乒乓球">乒乓球
    <input type="checkbox" v-model="hobbies" value="足球">足球
    <input type="checkbox" v-model="hobbies" value="籃球">籃球

    <h2>您選擇的是:{{hobbies}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            isAgree: false, //單選
            hobbies: [], // 多選
        },
        computed:{
            status(){
                let status = '';
                if (this.isAgree === false){
                    status = '不同意'
                }else{
                    status = '同意'
                }
                return status
            }
        }
    })
</script>
效果

v-model結合select

單選

<div id="app">
    <select name="abc" v-model="fruit">
        <option value="蘋果">蘋果</option>
        <option value="香蕉">香蕉</option>
        <option value="榴蓮">榴蓮</option>
        <option value="葡萄">葡萄</option>
    </select>
    <h2>您選擇的水果是:{{fruit}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            fruit:'香蕉'
        }
    })
</script>
效果

多選

<div id="app">
    <select name="abc" v-model="fruits" multiple>-->
        <option value="蘋果">蘋果</option>
        <option value="香蕉">香蕉</option>
        <option value="榴蓮">榴蓮</option>
        <option value="葡萄">葡萄</option>
    </select>
    <h2>您選擇的水果是: {{fruits}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            fruit: '香蕉',
            fruits:[]
        }
    })
</script>
效果

屬性值的繫結

<div id="app">
    <label for="item" v-for="item in originHobbies">
        <input type="checkbox" id="item" :value="item" :id="item" v-model="hobbies">{{item}}
    </label>

    <h2>您的愛好是: {{hobbies}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            hobbies: [],
            originHobbies: ['籃球', '足球', '乒乓球', '羽毛球', '檯球', '高爾夫球']
        }
    })
</script>

效果

修飾符

(1).lazy

在改變後才觸發(也就是說只有游標離開input輸入框的時候值才會改變)

<div id="app">
    <!--修飾符 lazy-->
    <!--在改變後才觸發(也就是說只有游標離開input輸入框的時候值才會改變)-->
    <input type="text" v-model.lazy="message">
    <h2>{{message}}</h2>

</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '',
            age: 0,
            name: ''
        }
    })
</script>
效果

(2).number

將輸出字串轉為Number型別·(雖然type型別定義了是number型別,但是如果輸入字串,輸出的是string)

<div id="app">
    <!--修飾符:number-->
    <!--將輸出字串轉為Number型別·(雖然type型別定義了是number型別,但是如果輸入字串,輸出的是string)-->
    <input type="number" v-model.number="age">
    <h2>{{age}}-{{typeof age}}</h2>

</div>

<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data:{
            message: '',
            age: 0,
            name: ''
        }
    })
</script>
效果

(3).trim

自動過濾使用者輸入的首尾空格

<body>
    <div id="app">
        <!--修飾符:trim  自動過濾使用者輸入的首尾空格-->
        <input type="text" v-model.trim="name">
        <h2>您輸入的名字:{{name}}</h2>

    </div>

    <script src="../js/vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data:{
                message: '',
                age: 0,
                name: ''
            }
        })
    </script>
</body>
效果
不考慮業務場景,一味的爭執技術的高下,都是耍流氓。