1. 程式人生 > 實用技巧 >Vue筆記 - [入門&指令]

Vue筆記 - [入門&指令]

vue是什麼?

  • Vue (讀音 /vjuː/,類似於 view) 是一套用於構建使用者介面的漸進式框架
  • vue 的核心庫只關注檢視層,不僅易於上手,還便於與第三方庫或既有專案整合

入門

通過CDN引入

 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

通過本地JS檔案引入

 <script src="vue.js路徑"></script>

入門程式碼

<div id="app">
    <h1>{{msg}}</h1>
</div>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            msg: 'Hello Vue!'
        }
    })
</script>
  • el : 元素的掛載位置(值可以是CSS選擇器或者DOM元素)
  • data : 模型資料(值是一個物件)
  • 插值表示式({{}}):
    • 將資料填充到HTML標籤中
    • 插值表示式支援基本的計算操作

指令

  • 本質就是自定義屬性
  • Vue中指定都是以 v- 開頭

v-cloak

  • 防止頁面載入時出現閃爍問題

    <div id="app">
        <h1 v-cloak>{{msg}}</h1>
    </div>
    
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg: 'Hello Vue!'
            }
        })
    </script>
    <style scope>
        [v-cloak]{
            /* 元素隱藏    */
            display: none;
        }
    </style>
    

v-text

  • v-text指令用於將資料填充到標籤中,作用於插值表示式類似,但是沒有閃動問題
  • 如果資料中有HTML標籤會將html標籤一併輸出
  • 注意:此處為單向繫結,資料物件上的值改變,插值會發生變化;但是當插值發生變化並不會影響資料物件的值
<div id="app">
    <h1 v-text="msg"></h1>
</div>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            msg: 'Hello Vue!'
        }
    })
</script>

v-html

  • 用法和v-text 相似 但是他可以將HTML片段填充到標籤中

  • 可能有安全問題, 一般只在可信任內容上使用 v-html永不用在使用者提交的內容上

  • 它與v-text區別在於v-text輸出的是純文字,瀏覽器不會對其再進行html解析,但v-html會將其當html標籤解析後輸出。

<div id="app">
   <div v-html="msg"></div>
</div>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            msg: '<h1>Hello Vue!</h1>'
        }
    })
</script>

v-pre

  • 顯示原始資訊跳過編譯過程

  • 跳過這個元素和它的子元素的編譯過程。

  • 一些靜態的內容不需要編譯加這個指令可以加快渲染

    <div id="app">
        <h1 v-pre>{{msg}}</h1>
    </div>
    
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg:'Hello World!'
            }
        })
    </script>
    

v-once

  • 執行一次性的插值【當資料改變時,插值處的內容不會繼續更新】

    <div id="app">
        <h1 v-once>{{msg}}</h1>
    </div>
    
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg: 'Hello Vue.js'
            }
        })
    </script>
    

雙向資料繫結

  • 當資料發生變化的時候,檢視也就發生變化
  • 當檢視發生變化的時候,資料也會跟著同步變化

v-model

  • v-model是一個指令,限制在 <input>、<select>、<textarea>、components中使用

    <div id="app">
        <h1>{{msg}}</h1>
        <!-- 當輸入框中內容改變的時候,  頁面上的msg  會自動更新 -->
        <input type="text" v-model="msg">
    </div>
    
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg: 'Hello Vue!'
            }
        })
    </script>
    

mvvm

  • MVC 是後端的分層開發概念; MVVM是前端檢視層的概念,主要關注於 檢視層分離,也就是說:MVVM把前端的檢視層,分為了 三部分 Model, View , VM ViewModel
  • m model
    • 資料層 Vue 中 資料層 都放在 data 裡面
  • v view 檢視
    • Vue 中 view 即 我們的HTML頁面
  • vm (view-model) 控制器 將資料和檢視層建立聯絡
    • vm 即 Vue 的例項 就是 vm

v-on

  • 用來繫結事件的

  • 形式如:v-on:click 縮寫為 @click;

    <div id="app">
        <h1>{{msg}}</h1>
        <button type="button" v-on:click="msg++">點選</button>
        <button type="button" @click="msg++">點選1</button>
        <button type="button" @click="handle">點選2</button>
    </div>
    
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg: 0
            },methods:{
                handle:function () {
                    this.msg++;
                }
            }
        })
    </script>
    
  • 事件函式的呼叫方式:

    • 直接繫結函式名稱

      <button v-on:click='say'>Hello</button>
      
    • 呼叫函式

      <button v-on:click='say()'>Say hi</button>
      
  • 事件函式 - 引數傳遞

    <div id="app">
        <h1>{{msg}}</h1>
        <!-- 如果事件直接繫結函式名稱,那麼預設會傳遞事件物件作為事件函式的第一個引數 -->
        <button v-on:click='handle1'>點選1</button>
        <!-- 2、如果事件繫結函式呼叫,那麼事件物件必須作為最後一個引數顯示傳遞,
             並且事件物件的名稱必須是$event
        -->
        <button type="button" @click="changeMsg('你好Vue!',$event)">點我改變</button>
    </div>
    <script>
        let app = new Vue({
            el: '#app',
            data: {
                msg: 'Hello Vue!'
            },
            methods:{
                handle1: function (event) {
                    console.log(event.target.innerHTML);
                },
                changeMsg:function (message,event) {
                    this.msg = message;
                    console.log(event.target.innerHTML);
                }
            }
        })
    </script>
    

事件修飾符

  • 在事件處理程式中呼叫 event.preventDefault()event.stopPropagation() 是非常常見的需求。
  • Vue 不推薦我們操作DOM 為了解決這個問題,Vue.js 為 v-on 提供了事件修飾符
  • 修飾符是由點開頭的指令字尾來表示的
<!-- 阻止單擊事件繼續傳播 -->
<a v-on:click.stop="doThis"></a>

<!-- 提交事件不再過載頁面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 修飾符可以串聯   即阻止冒泡也阻止預設事件 -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- 只當在 event.target 是當前元素自身時觸發處理函式 -->
<!-- 即事件不是從內部元素觸發的 -->
<div v-on:click.self="doThat">...</div>

使用修飾符時,順序很重要;相應的程式碼會以同樣的順序產生。因此,用 v-on:click.prevent.self 會阻止所有的點選,而 v-on:click.self.prevent 只會阻止對元素自身的點選。
<div id="app">
    <h1>{{num}}</h1>
    <div v-on:click="add">
        <button type="button" v-on:click.stop="change">change</button>
    </div>
    <a href="https://www.baidu.com" v-on:click.prevent="change">百度</a>
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            msg: 'Hello Vue!',
            num: 0
        },
        methods:{
            add: function () {
                this.num++;
            },
            change: function () {
            }
    	}
    })
</script>

按鍵修飾符

  • 在做專案中有時會用到鍵盤事件,在監聽鍵盤事件時,我們經常需要檢查詳細的按鍵。Vue 允許為 v-on 在監聽鍵盤事件時新增按鍵修飾符
<div id="app">
    預先定義了keycode 116(即F5)的別名為f5,因此在文字輸入框中按下F5,會觸發prompt方法
    <input type="text" v-on:keydown.f5="prompt()">
</div>
<script>
    Vue.config.keyCodes.f5 = 116;
    let app = new Vue({
        el: '#app',
        methods: {
            prompt: function() {
                alert('我是 F5!');
            }
        }
    });
</script>

小案例 - 計算器

<div id="app">
    <h1>簡單計算器</h1>
    <div>
        <span>數值A:</span>
        <span>
            <input type="text" v-model="a">
        </span>
    </div>
    <div>
        <span>數值B:</span>
        <span>
            <input type="text" v-model="b">
        </span>
    </div>
    <div>
        <button type="button" @click="calc">計算</button>
    </div>
    <div>
        <span>計算結果: </span>
        <span v-text="result"></span>
    </div>
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            a: '',
            b: '',
            result: ''
        },
        methods:{
            calc: function () {
                this.result = parseInt(this.a) + parseInt(this.b);
            }
        }
    })
</script>

v-bind

  • v-bind 指令被用來響應地更新 HTML 屬性
  • v-bind:href 可以縮寫為 :href;
<div id="app">
    <a v-bind:href="url">百度</a>
    <!-- v-bind的簡寫形式-->
    <a :href="url">百度</a>
</div>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            url: 'https://www.baidu.com'
        }
    })
</script>

使用v-bind實現雙向繫結

<div id="app">
    <h1>{{msg}}</h1>
    <input type="text" v-bind:value="msg" v-on:input="handle">
    <input type="text" v-bind:value="msg" v-on:input="msg = $event.target.value">
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            msg: 'Hello Vue!'
        },
        methods:{
            handle: function (event) {
                this.msg = event.target.value;
            }
        }
    })
</script>

繫結物件

  • 我們可以給v-bind:class 一個物件,以動態地切換class。
  • 注意:v-bind:class指令可以與普通的class特性共存
<!-- 1、 v-bind 中支援繫結一個物件 
	如果繫結的是一個物件 則 鍵為 對應的類名  值 為對應data中的資料 
-->
<!-- 
	HTML最終渲染為 <ul class="box textColor textSize"></ul>
	注意:
		textColor,textSize  對應的渲染到頁面上的CSS類名	
		isColor,isSize  對應vue data中的資料  如果為true 則對應的類名 渲染到頁面上 


		當 isColor 和 isSize 變化時,class列表將相應的更新,
		例如,將isSize改成false,
		class列表將變為 <ul class="box textColor"></ul>
-->
<ul class="box" v-bind:class="{textColor:isColor, textSize:isSize}">
    <li>學習Vue</li>
    <li>學習Node</li>
    <li>學習React</li>
</ul>
  <div v-bind:style="{color:activeColor,fontSize:activeSize}">物件語法</div>
<sript>
var vm= new Vue({
    el:'.box',
    data:{
        isColor:true,
        isSize:true,
    	activeColor:"red",
        activeSize:"25px",
    }
})
</sript>
<style>
    .box{
        border:1px dashed #f0f;
    }
    .textColor{
        color:#f00;
        background-color:#eef;
    }
    .textSize{
        font-size:30px;
        font-weight:bold;
    }
</style>

繫結class

2、  v-bind 中支援繫結一個數組    陣列中classA和 classB 對應為data中的資料

這裡的classA  對用data 中的  classA
這裡的classB  對用data 中的  classB
<ul class="box" :class="[classA, classB]">
    <li>學習Vue</li>
    <li>學習Node</li>
    <li>學習React</li>
</ul>
<script>
var vm= new Vue({
    el:'.box',
    data:{
        classA:‘textColor‘,
        classB:‘textSize‘
    }
})
</script>
<style>
    .box{
        border:1px dashed #f0f;
    }
    .textColor{
        color:#f00;
        background-color:#eef;
    }
    .textSize{
        font-size:30px;
        font-weight:bold;
    }
</style>

繫結物件和繫結陣列 的區別

  • 繫結物件的時候 物件的屬性 即要渲染的類名 物件的屬性值對應的是 data 中的資料
  • 繫結陣列的時候數組裡面存的是data 中的資料
<div id="app">
   <div :class="[errorClass,bgClass,{active:isActive}]">
       <h1>test</h1>
   </div>
    <div :class="classes"></div>
    <div :class="objClass"></div>

    <div class="bg" :class="objClass"></div>
    <button type="button" @click="change">切換</button>
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            errorClass:'error',
            bgClass:'bg',
            isActive:false,
            classes:['error','bg','active'],
            objClass:{
                active:true,
                error:true
            }
        },
        methods:{
            change:function () {
                this.isActive = !this.isActive;
            }
        }
    })
</script>
<style scope>
    .active{
        width: 100px;
        height: 100px;
        border: 1px solid red;
    }
    .error{
        color: red;
    }
    .bg{
        background: deepskyblue;
    }
</style>

繫結style

<div v-bind:style="styleObject">繫結樣式物件</div>'
 
<!-- CSS 屬性名可以用駝峰式 (camelCase) 或短橫線分隔 (kebab-case,記得用單引號括起來)    -->
 <div v-bind:style="{ color: activeColor, fontSize: fontSize,background:'red' }">內聯樣式</div>

<!--組語法可以將多個樣式物件應用到同一個元素 -->
<div v-bind:style="[styleObj1, styleObj2]"></div>

<script>
	new Vue({
      el: '#app',
      data: {
        styleObject: {
          color: 'green',
          fontSize: '30px',
          background:'red'
        },
        activeColor: 'green',
   		fontSize: "30px"
      },
      styleObj1: {
             color: 'red'
       },
       styleObj2: {
            fontSize: '30px'
       }

</script>

分支結構

v-if 使用場景

  • 1- 多個元素 通過條件判斷展示或者隱藏某個元素。或者多個元素
  • 2- 進行兩個檢視之間的切換
<div id="app">
        <!--  判斷是否載入,如果為真,就載入,否則不載入-->
        <span v-if="flag">
           如果flag為true則顯示,false不顯示!
        </span>
</div>

<script>
    var vm = new Vue({
        el:"#app",
        data:{
            flag:true
        }
    })
</script>

----------------------------------------------------------

<div v-if="type === 'A'">
    A
</div>
<!-- v-else-if緊跟在v-if或v-else-if之後   表示v-if條件不成立時執行-->
<div v-else-if="type === 'B'">
    B
</div>
<div v-else-if="type === 'C'">
    C
</div>
<!-- v-else緊跟在v-if或v-else-if之後-->
<div v-else>
    Not A/B/C
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            type: 'C'
        }
    })
</script>

v-show 和 v-if的區別

  • v-show本質就是標籤display設定為none,控制隱藏
    • v-show只編譯一次,後面其實就是控制css,而v-if不停的銷燬和建立,故v-show效能更好一點。
  • v-if是動態的向DOM樹內新增或者刪除DOM元素
    • v-if切換有一個區域性編譯/解除安裝的過程,切換過程中合適地銷燬和重建內部的事件監聽和子元件
<div id="app">
   <div v-if="score >= 90">優秀</div>
   <div v-else-if="score>=80 && score <90">良好</div>
   <div v-else-if="score>=60 && score <80">一般</div>
   <div v-else-if="score>=0 && score <60">比較差</div>
    <div v-show="flag"><h1>測試v-show</h1></div>
    <button type="button" @click="handle">顯示</button>
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            score: 80,
            flag: false
        },
        methods:{
            handle:function (event) {

                if (this.flag){
                    event.target.innerHTML = '顯示';
                }else{
                    event.target.innerHTML = '隱藏';
                }
                this.flag = !this.flag;
            }
        }
    })
</script>

迴圈結構

v-for

  • 用於迴圈的數組裡面的值可以是物件,也可以是普通元素
<ul id="example-1">
   <!-- 迴圈結構-遍歷陣列  
	item 是我們自己定義的一個名字  代表數組裡面的每一項  
	items對應的是 data中的陣列-->
  <li v-for="item in items">
    {{ item.message }}
  </li> 

</ul>
<script>
 new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ],
   
  }
})
</script>
  • 不推薦同時使用 v-ifv-for
  • v-ifv-for 一起使用時,v-for 具有比 v-if 更高的優先順序。
 <!--  迴圈結構-遍歷物件
		v 代表   物件的value
		k  代表物件的 鍵 
		i  代表索引	
	---> 
     <div v-if='v==13' v-for='(v,k,i) in obj'>{{v + '---' + k + '---' + i}}</div>

<script>
 new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ],
    obj: {
        uname: 'zhangsan',
        age: 13,
        gender: 'female'
    }
  }
})
</script>

key 的作用

  • key來給每個節點做一個唯一標識
  • key的作用主要是為了高效的更新虛擬DOM
<ul>
  <li v-for="item in items" :key="item.id">...</li>
</ul>
<div id="app">
    <ul>
<!--        <li v-for="item in fruits">{{item}}</li>-->
<!--        <br>-->
        <li v-for="(item,index) in fruits">{{index + '----'+ item}}</li>
    </ul>
    <ul>
        <!-- key來給每個節點做一個唯一標識 -->
        <li v-for="(item,index) in myFruits" :key="item.id">
            索引:{{index}}
            <br>
            英文:{{item.ename}}
            <br>
            中文:{{item.cname}}
        </li>
    </ul>
</div>

<script>
    let app = new Vue({
        el: '#app',
        data: {
            fruits: ['apple', 'orange', 'banana'],
            myFruits:[
                {
                    id: 1,
                    ename:'apple',
                    cname:'蘋果'
                },
                {
                    id: 2,
                    ename:'orange',
                    cname:'橙子'
                },
                {
                    id: 3,
                    ename:'banana',
                    cname:'香蕉'
                }
            ]
        }
    })
</script>

小案例

<div id="app">
    <div class="tab">
        <ul>
            <li @click="change(index)" :class='currentIndex==index?"active":""' :key="item.id" v-for="(item,index) in list">{{item.title}}</li>
        </ul>
        <div :class='currentIndex==index?"current":""'  v-for="(item,index) in list">
            <img :src="item.path"  alt=""/>
        </div>
    </div>
</div>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            currentIndex:0,
            list:[
                {
                    id:1,
                    title:'apple',
                    path:'img/apple.png'
                },
                {
                    id:2,
                    title:'orange',
                    path:'img/orange.png'
                },
                {
                    id:3,
                    title:'lemon',
                    path:'img/lemon.png'
                }
            ]
        },
        methods:{
            change: function (index) {
                this.currentIndex = index;
            }
        }
    })
</script>
<style scope>
    .tab ul {
        overflow: hidden;
        padding: 0;
        margin: 0;
    }

    .tab ul li {
        box-sizing: border-box;
        padding: 0;
        float: left;
        width: 100px;
        height: 45px;
        line-height: 45px;
        list-style: none;
        text-align: center;
        border-top: 1px solid blue;
        border-right: 1px solid blue;
        cursor
    }

    .tab ul li:first-child {
        border-left: 1px solid blue;
    }

    .tab ul li.active {
        background-color: orange;
    }

    .tab div {
        width: 500px;
        height: 300px;
        display: none;
        text-align: center;
        font-size: 30px;
        line-height: 300px;
        border: 1px solid blue;
        border-top: 0px;
    }

    .tab div.current {
        display: block;
    }
</style>