VUE-02-v-model和過濾器
昨日反饋與回顧
代碼倉庫的問題
不要修改你克隆下來的倉庫中任意代碼,否則,下次pull時,可能會報錯,從而得到不到最新的代碼。
如果已經遇到了這個沖突:
- 解決沖突(git 中解決沖突)
- 把關鍵代碼拷出來,放棄這個倉庫,重新再次clone(后續git pull)
處理樣式
樣式由兩個部分決定:
- class
- style
v-bind綁定class
目標:知道通過vue怎么去操作類,也就是class屬性的值。
動態綁定class屬性,有三種方式:
- 三元運算符
- 綁定對象:如果屬性值為true,則添加屬性名給class
- 綁定數組
代碼:
<style>#app{width:500px;margin:50px auto;border:3px solid red;}.box{border:3px solid black;margin:5px;}.bg-blue{background-color: blue;}.bg-green{background-color: green;}.fs20{font-size:20px;}.tr{text-align: right;}</style>
</head>
<body><div id="app"><h3 class="title">v-bind-綁定class</h3><!-- 元素自有class和v-bind綁定的class會協同工作,一起生效 --><div class="box" v-bind:class="cla ? 'bg-blue': 'bg-green'">1. 三元表達式</div><!-- 如果對象中的屬性值是true,則把對象中的屬性名添加到類名中 --><div class="box" :class="claObj">2. 綁定對象</div><!-- 數組中元素是字符串,它會把所有的元素全添加到class中 --><div class="box" :class="claArr">3. 綁定數組</div><button @click="hAddClass">補充一個class</button></div><script>// v-bind 是用來動態綁定元素的屬性,而class也是元素的屬性// 目標: 可以通過動綁定class來控制樣式 。// 方式:// 1. 三元表達式// 2. 綁定對象// 3. 綁定數組const vm = new Vue({el: "#app",// el: document.getElementById("app"),data: {cla: false,claObj: {fs20: true,tr: true},claArr:['fs20','tr', 'abc']},methods: {hAddClass () {// 向數組中添加一個類 'c-red'this.claArr.push('c-red')}}})</script>
:class
動態綁定類名 class
原生屬性,可以同時存在,他們包含的所有類會合并在一起生效。
v-bind綁定style
目標:知道通過vue怎么去操作行內樣式,也就是style屬性的值。
動態綁定style屬性有兩種方式:
- 對象形式
- 數組形式
v-bind綁定style使用對象:
<div id="app"><h3 class="title">v-bind-綁定style</h3><!-- 把對象的屬性名和屬性值直接設置到style中 --><div class="box" :style="styleObj">1. 綁定對象</div><!-- 把數組中的每一個元素(對象),取出來,組成style --><div class="box" :style="styleArr">2. 綁定數組</div><button @click="hBlack">改成黑色的字</button></div><script>// v-bind 是用來動態綁定元素的屬性,而style也是元素的屬性// 目標: 可以通過動綁定style來控制樣式 。// 方式:// 1. 綁定對象// 2. 綁定數組const vm = new Vue({el: "#app",// el: document.getElementById("app"),data: {styleObj: {color:'red',// 如果屬性名有-,則要加'''background-color':'blue'},// 數組中的每一項都是一個對象,其中以鍵值對的格式設置了stylestyleArr:[ {color:'red','font-weight':'bold'}, {'font-size':'50px'} ]},methods: {hBlack () {// 直接把styleObj中的color設置成blackthis.styleObj.color = "black"}}})</script>
如果同時存在 :style 和 style vue操作的樣式會覆蓋默認樣式。
總結:
- :style 使用對象 {css屬性名:css屬性值}
- :style 使用數組 [{css屬性名:css屬性值}]
v-model
目標
知道如何綁定多種類型的表單元素
基本使用
<div id="app"><h3 class="title">v-model</h3>用戶名:<input v-model="userName" ><br><!-- 不是表單元素不能用<div v-model="userName" ></div> --><button @click="userName=123">123</button><button @click="hPrint">打出userName</button></div><script>// v-model // 是用來對表單元素進行雙向綁定的。// 表單元素: 用戶可以進行交互的元素,textarea,select,input,checkbox...// 雙向綁定: // -1. 用戶在input中的修改,會影響到數據// -2. 數據的修改會影響input// 格式:<表單元素 v-model="數據項">const vm = new Vue({el: "#app",data: {userName: '小王'},methods: {hPrint () {console.log( this.userName )}}})</script>
表單元素
- 文本域
- 復選框
- 單選框
- 下拉框
<div id="app"><h3 class="title">v-model</h3><div class="box"><!-- 1. 普通文本框 -->用戶名:<input v-model="userName" ></div><div class="box"><!-- 2. 單選 由value來決定用戶選中的值 -->性別:<input type="radio" value="男" v-model="gender">帥哥<input type="radio" value="女" v-model="gender">美女</div><div class="box"><!-- 3. 復選 由value來決定用戶選中的值,結果放在一個數組中 -->愛好:<input type="checkbox" value="讀書" v-model="hobby">讀書<input type="checkbox" value="sport" v-model="hobby">運動<input type="checkbox" value="k歌" v-model="hobby">k歌</div><div class="box"><!-- 4. 文本域 注: 不能把內容寫在元素中: <textarea v-model="info">abc</textarea>-->個人說明:<textarea v-model="info"></textarea></div><div class="box"><!-- 5. 下拉選中的值是以value為準-->位置: <select v-model="city"><option value="1">北京</option><option value="2">上海</option><option value="3">潛江</option></select></div><div class="box"><!-- 6. 單個復選框(是否同意)如果為true,則選中,false,不選中-->愿意嗎?<input type="checkbox" v-model="isChecked"></div><button @click="hPrint">打印結果</button></div><script>// v-model // 是用來對表單元素進行雙向綁定的。// 1. 普通文本框 // 2. 單選// 3. 復選// 4. 文本域// 5. 下拉// 6. 單個復選框(是否同意)const vm = new Vue({el: "#app",data: {userName: '小王子',gender:'男', // 單選hobby:['讀書'], // 多選info: '自我介紹,如下:白玉誰家郎',city: 1,isChecked: false},methods: {hPrint () {console.log( this.userName )console.log( this.gender )console.log( this.hobby )console.log( this.info )console.log( this.city )console.log( this.isChecked )}}})</script>
修飾符
lazy
在默認情況下,v-model
在每次 input
事件觸發后將輸入框的值與數據進行同步。你可以添加 lazy
修飾符,從而轉為在 change
事件_之后_進行同步:
<!-- 在“change”時而非“input”時更新 -->
<input v-model.lazy="msg">
number
如果想自動將用戶的輸入值轉為數值類型,可以給 v-model
添加 number
修飾符:
<input v-model.number="age" type="number">
這通常很有用,因為即使在 type="number"
時,HTML 輸入元素的值也總會返回字符串。如果這個值無法被 parseFloat()
解析,則會返回原始的值。
trim
如果要自動過濾用戶輸入的首尾空白字符,可以給 v-model
添加 trim
修飾符:
<input v-model.trim="msg">
<div id="app"><h3 class="title">v-model</h3><div class="box"><!-- 1. lazy --><!-- 不加lazy:<input v-model="userName" >{{userName}} --><br>加lazy:<input v-model.lazy="userName" >{{userName}}</div><div class="box"><!-- 2. number 不加number,就是一個普通的字符串加了number,會盡量幫你轉成數值,轉不成,也不會報錯--><br>加number:<input v-model.number="age" >{{age}}</div><div class="box"><!-- 3. trim 自動把內容中的前后空格去掉--><br><input v-model.trim="email" >內容的長度:{{email.length}}</div></div><script>// v-model // v-model的三個修飾符// 1. lazy --> v-model.lazy="userName"// 默認情況,v-model只要用戶修改了input中的內容(在每次input事件之后)就會與數據進行同步// 如果加了lazy之后,則在用戶完成了輸入,鼠標失焦之后(相當于change),才會與數據同步。// 2. number// 自動轉成數值的格式// 3. trim// 把內容中的前后空格去掉const vm = new Vue({el: "#app",data: {userName: '小王',age:18,email:''},methods: {hPrint () {console.log( this.userName )}}})</script>
案例-資產列表
渲染列表
目標:完成表格列表渲染。
需求:
- 根據data中的數據,進行tr的渲染。
- 當沒有數據的時候,顯示暫無數據。
靜態頁面:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="stylesheet" href="./bootstrap.min.css">
</head>
<body><div id="app"><div class="container"><table class="table table-bordered table-hover"><thead><tr><th>編號</th><th>資產名稱</th><th>創建時間</th><th>操作</th></tr></thead><tbody><tr><td>1</td><td>寶馬</td><td>20000</td><td><a href="#">刪除</a></td></tr></tbody></table></div></div>
</body>
</html>
準備數據:
list: [{ id: 1, name: '外套', price: 99 },{ id: 2, name: '褲子', price: 34 },{ id: 3, name: '鞋', price: 25.4 },{ id: 4, name: '頭發', price: 19900 }
]
完整的功能實現:
<div id="app"><div class="container"><table class="table table-bordered table-hover"><thead><tr><th>編號</th><th>資產名稱</th><th>創建時間</th><th>操作</th></tr></thead><tbody><!-- <tr v-for="(循環變量,索引變量) in 數據"> --><tr v-for="(item, idx) in list"><td>{{item.id}}</td><td>{{item.name}}</td><!-- 如果價格超過100,就有red這個類 --><!-- <td class="red">{{item.price}}</td> --><!-- 三元--><!-- <td :class='item.price > 100 ? "red" : ""'>{{item.price}}</td> --><!-- 放一個對象如果對象中的屬性值是true,則把對象中的屬性名添加到類名中--><td :class="{red:item.price>100}">{{item.price}}</td><td><a href="#" @click.prevent="hDel(idx)">刪除</a></td></tr></tbody></table></div></div><script src="./vue.js"></script><script>const vm = new Vue({el: '#app',data: {list: [{ id: 1, name: '外套', price: 99 },{ id: 2, name: '褲子', price: 34 },{ id: 3, name: '鞋', price: 25.4 },{ id: 4, name: '頭發', price: 19900 }]}})</script>
刪除功能
目標:完成表格一行刪除。
需求:
- 點擊刪除按鈕,確認框提示
- 點擊確認后,再進行刪除
- 綁定事件,指定處理函數的時候,傳入ID
- 在處理函數中,根據ID進行刪除(id===>index====>根據索引刪除)
實現:
<td><a @click.prevent="hDel(idx)" href="#">刪除</a></td>
methods: {hDel (index) {console.log('要刪除的下標是',index)// 刪除數組中指定位置的元素this.list.splice(index, 1)}
}
添加資產
目標:完成表格添加資產。
大致的實現步驟:
- 準備一個表單,包含一個輸入框,包含一個提交按鈕。
- 監聽提交事件,提取輸入框中的內容
- 根據輸入的內容來組織 資產信息對象 追加到數組中即可
- 數據會驅動視圖的更新
- 清空輸入框中的內容
在案例中的代碼:
html結構
<!-- 添加資產 -->
<form class="form-inline"><div class="form-group"><div class="input-group"><input type="text" class="form-control" placeholder="資產名稱"></div></div> <button class="btn btn-primary">添加資產</button>
</form>
雙向綁定輸入框
<input v-model.trim="brandName" type="text" class="form-control" placeholder="資產名稱">
- 監聽提交事件,且阻止默認提交行為
<form @submit.prevent="addBrand()" class="form-inline">
- 在處理函數中實現邏輯
// 添加資產addBrand() {// 通過v-model綁定輸入框,可以實時的獲取輸入的內容// console.log(this.brandName)// 嚴謹判斷,未輸入內容,提示 + 阻止程序運行// trim()是去除字符串左右兩側的空格,然后去判斷會更加嚴謹if (!this.brandName.trim()) {return alert('請輸入資產名稱')}// 組織一個對象:id brandName createTime// 正常邏輯:去除數組中最后一項數據的ID累加1即可// 極端情況:數組中已經沒有數據,此時ID為1即可const obj = {id: this.list.length ? this.list[this.list.length - 1].id + 1 : 1,brandName: this.brandName,createTime: new Date()}// 追加到數組中即可this.list.push(obj)// 清空輸入框this.brandName = ''}
梳理其它功能
目標:確定還有哪些功能需要完成。
輸入框結構:
<!-- 搜索 --><form class="form-inline" style="padding: 20px 0"><input type="text" class="form-control" placeholder="輸入關鍵字進行搜索"></form><!-- 表格 -->
過濾器
目標:
- 理解過濾器的作用和使用場景
- 掌握定義和使用過濾器。
理解過濾器
過濾器的作用:轉換格式。
生活中的過濾器:
如:把水中的雜質過濾掉。輸入過濾器的是臟水,輸出的是純凈水。
vue中的過濾器:
- 如:把字符串用0補足6位。輸入的是不足6位的字符串,輸出的是用0補全之后的字符串。
- 如:把單詞首字母轉成大寫。輸入的是普通單詞,輸出的是首字母大寫的單詞。
本質就是一個函數
格式x ---過濾器----> 格式y
格式
定義過濾器的格式
new Vue({// 過濾器的定義filters: {// 屬性名稱(過濾器名稱):屬性的值(過濾器處理函數)myFilter:function(value,其它參數){}}})
使用過濾器的格式
// 不帶參數
{{ msg | 過濾器}}
// 帶參數
{{ msg | 過濾器(參數)}}
示例1:不帶參數的過濾器
<div id="app"><h3>{{msg}}</h3><!-- 使用過濾器 --><h3>{{msg | f1}}</h3><!-- 使用過濾器 --><h3>{{msg | padding6}}</h3></div><script>// vue中的過濾器// 作用: 在顯示數據之前,做一次格式轉化// 定義格式// filters: {// 過濾器名: function (value,其它參數) {// }// }// 使用格式 // {{ msg | 過濾器}}// {{msg}} =====> console.log(msg)// {{msg | f1}} =====> console.log( f1(msg) )const vm = new Vue({el: "#app",data: {msg: 'vue'},// 過濾器列表filters: {// {{msg | f1}}// 會去:// 1. 調用f1這個函數,并自動把msg傳進來給value// 2. 把f1函數的返回值顯示出來f1 (value) {console.log(value)return 'hahaha'},padding6 (str) {// 對于字符串,不足6位,// 左側補0// String(str) 類型轉換// padStart: 在左側補足字符串//字符串.padStart(總長度,填充的字符)return String(str).padStart(6, "*")}}})
</script>
注意:
-
它的工作過程就是函數的調用執行過程。
-
過濾器本質是一個函數:它的接收的參數是格式化之前的數據及格式化的參數,它的返回值是格式化之間的值
示例2:帶參數過濾器
定義:
filters: {// {{msg | f1}}// 會去:// 1. 調用f1這個函數,并自動把msg傳進來給value// 2. 把f1函數的返回值顯示出來f1 (value) {console.log(value)return 'hahaha'},paddingN (str,n) {// 對于字符串,不足n位,左側補0// String(str) 類型轉換// padStart: 在左側補足字符串//字符串.padStart(總長度,填充的字符)return String(str).padStart(n, "*")}}
使用:
{{ "ab" | padding6}}
{{ name | padding(5)}}
注意:
- 它會自動傳入第一個參數。
過濾器的分類
-
全局過濾器(在vue實例外部定義,在隨后的每個vue實例中均可使用)
Vue.filter('過濾器名稱',function(value){ //管道符前js表達式執行結果 // 返回處理好的數據即可 })
-
局部過濾器(在vue實例中定義,僅能給當前vue實例管理的視圖使用)
總結:
- 全局
Vue.filter('過濾器名稱',(value)=>{ //管道符前js表達式執行結果 // 返回處理好的數據即可 })
- 局部
new Vue({filters:{'過濾器名稱':(value)=>{ //管道符前js表達式執行結果 // 返回處理好的數據即可 }}})
自定義指令
目標:知道如何定義自定義指令,使用自定義指令。
指令(directive)vue提供了v-開頭的特殊屬性,稱之為指令。它提供的指令是有限,如果遇見內置指令無法給你實現的功能,自己封裝一個指令(自定義指令)。
定義一個v-focus的指令,作用讓input自動獲取焦點
全局自定義指令,局部自定義指令
<div id="app"><input type="text" v-focus><input type="text" v-myfocus></div><script src="./vue.js"></script><script>// 全局自定義指令// Vue.directive('指令的名稱','指令配置對象')// 參數1:指令的名稱,不包含v-,但是在使用指令的時候需要加上v-// 參數2:指令配置對象,固定屬性 inserted 指定的一個函數,// 1. 該函數會在通過指令標記的元素,創建完畢之后執行// 2. 該函數有一個默認參數 el 指的是使用這個指令的元素Vue.directive('focus',{inserted (el) {// 獲取焦點el.focus()}})const vm = new Vue({el: '#app',// 局部自定義指令// vue配置對象提供了一個選項:directives 對應 對象directives: {// 屬性名稱(指令的名稱):屬性的值(指令的配置對象)myfocus: {inserted (el) {el.style.height = '50px'el.focus()}}}})</script>
補充:
- dom元素提供了focus函數,dom.focus()觸發獲取焦點事件,自然元素可以獲取焦點。
案例-資產列表(續)
用過濾器完成貨幣格式化顯示
filters: {$:function(value, _currency) {// 全局匹配: 三位連續,且之后也是數值 的數值var digitsRE = /(\d{3})(?=\d)/g;value = parseFloat(value);if (!isFinite(value) || !value && value !== 0) return '';_currency = _currency != null ? _currency : '¥';// 保留兩位小數,并整體轉成字符串var stringified = Math.abs(value).toFixed(2);// 獲取整數部分。-3表示倒數3位的位置var _int = stringified.slice(0, -3);// 整數部分以3為基準長度劃分,剩下幾位var i = _int.length % 3;// 取出頭部。// 如:12345 ----> 12,var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : '';// 取出小數點部分// 如:12345.67 ----> .67var _float = stringified.slice(-3);var sign = value < 0 ? '-' : '';return _currency + sign + head + _int.slice(i).replace(digitsRE, '$1,') + _float;}
}
用自定義指令來完成搜索框自動獲取焦點
directives: {// 屬性名稱(指令的名稱):屬性的值(指令的配置對象)myfocus: {inserted (el) {el.focus()}}
}
用過濾器完成貨幣格式化顯示。
注意:下面的代碼來自vue1中的源碼。在vue1中提供了貨幣金額顯示格式化的過濾器currency,請在這里https://cdn.bootcdn.net/ajax/libs/vue/1.0.11/vue.js搜索currency關鍵字。
filters: {$:function(value, _currency) {// 全局匹配: 三位連續,且之后也是數值 的數值var digitsRE = /(\d{3})(?=\d)/g;value = parseFloat(value);if (!isFinite(value) || !value && value !== 0) return '';_currency = _currency != null ? _currency : '¥';// 保留兩位小數,并整體轉成字符串var stringified = Math.abs(value).toFixed(2);// 獲取整數部分。-3表示倒數3位的位置var _int = stringified.slice(0, -3);// 整數部分以3為基準長度劃分,剩下幾位var i = _int.length % 3;// 取出頭部。// 如:12345 ----> 12,var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : '';// 取出小數點部分// 如:12345.67 ----> .67var _float = stringified.slice(-3);var sign = value < 0 ? '-' : '';return _currency + sign + head + _int.slice(i).replace(digitsRE, '$1,') + _float;}
}
用自定義指令來完成搜索框自動獲取焦點
directives: {// 屬性名稱(指令的名稱):屬性的值(指令的配置對象)myfocus: {inserted (el) {el.focus()}}
}