傳說中 VUE 的“語法糖”到底是啥?


一、什么是語法糖?

語法糖也譯為糖衣語法,是由英國計算機科學家彼得·約翰·蘭達(Peter J. Landin)發明的一個術語。指的是計算機語言中添加的一種語法,在不影響功能的情況下,添加某種簡單的語法也能實現效果,這種語法對計算機沒有任何影響,但是對於程序員更方便,通常增加的語法糖能夠增加程序員的可讀性,減少出錯的機會。

使用語法糖可以簡化代碼,更便於程序員開發。

二、VUE中語法糖有哪些?

1、最常見的語法糖 v-model

使用 v-model 可以實現數據雙向綁定,但是如何實現的呢?

v-model 綁定數據之后,既綁定了數據,又添加了事件監聽,這個事件就是 input 事件。

使用案例:

//語法糖寫法
<input type="text" v-model="name" > //還原為以下實例 <input type="text" v-bind:value="name" v-on:input="name=$event.target.value">

輸入的時候會觸發 input 事件,input 事件會把當前值賦值給 value ,這就是 v-model 為什么可以實現雙向綁定的原因。

2、v-bind 的語法糖

v-bind 用來添加動態屬性的,常見的 src、href、class、style、title 等屬性都可以通過 v-bind 添加動態屬性值。

v-bind 的語法糖就是去掉 v-bind 替換成冒號 (:)

// 語法糖寫法 <div :title="title"> <img :src="url" alt=""> <a :href="link">沒有語法糖</a> </div> // 沒有語法糖 <div v-bind:title="title"> <img v-bind:src="url" alt=""> <a v-bind:href="link">沒有語法糖</a> </div>

3、v-on 的語法糖

v-on 綁定事件監聽器的,v-on 的語法糖,就是簡寫成@ 。

情況1:如果方法不傳參時,可以不加小括號。

<button @click="btn">語法糖</button> <button v-on:click="btn">無語法糖</button> //需要注意的是,如果方法本身有一個參數,會默認將原生的事件event參數傳遞進來 methods:{ btn( event ){ console.log( 'event' , event ) } }

情況2:如果需要傳遞參數時,又同時需要 event 參數。

<button @click="btn( '點擊事件' , $event )">語法糖</button> //需要注意的是,$event 事件拿到瀏覽器事件對象 methods:{ btn( type, event ){ console.log( 'type' , type ) //點擊事件 console.log( 'event' , event ) } }

4、修飾符

修飾符是以半角句號 . 指明的特殊后綴。v-on 后面的修飾符,也是語法糖。

示例:鏈接添加點擊事件,點擊之后不希望跳轉。

//語法糖 <a href="http://www.baidu.com" @click.prevent="go">百度</a> //普通寫法 <a href="http://www.baidu.com" v-on:click="go">百度</a> methods:{ go(e){ e.preventDefault(); console.log('阻止鏈接跳轉') } }

prevent 修飾符是阻止默認事件。還有 submit 同樣也適用。

<form @submit.prevent="onSubmit"></form>

下列是常見的修飾符,與上邊 .prevent 使用相同。

  • .stop 用來阻止事件冒泡。
  • .once 事件只觸發一次。
  • .self 事件只在自身觸發,不能從內部觸發。
  • .enter | .tab | .delete | .esc ..... 鍵盤修飾符
  • .ctr | .alt | .shift | .meta 系統修飾符

5、動態css

使用 v-bind 可以通過 style 或 class, 可以添加動態樣式。

//點擊 你好,實現文字紅黑之間切換 <h1 @click=" changeColor = !changeColor " :style="{color:changeColor?'red':'black'}"> 你好 </h1> data:{ changeColor:false }

6、注冊組件語法糖

所謂的注冊組件語法糖是指省去組件構造器的定義,直接將組件構造器對象傳入注冊組件函數里,這樣會減少 CPU 的調度以及內存的分配。

全局組件使用:

//全局組件語法糖寫法 Vue.component( 'my-component' , template:` <div>組件內容</div> `) /* 全局組件注冊 */ //組件使用 <my-component></my-component> //注冊組件 const myComponent = Vue.extend({ template:` <div> <h2>VUkeh</h2> </div> ` }) Vue.component('myComponent', myComponent)

局部組件使用:

//全局組件語法糖寫法 components:{ 'my-component':{ template:`<div>組件內容</div>` } } /* 局部組件注冊 */ //注冊組件 const myComponent = Vue.extend({ template:` <div> <h2>VUkeh</h2> </div> `, components:{ child:{ template:`<div>子組件內容</div>` } } }) Vue.component('myComponent', myComponent)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM