前端筆記Vue項目day2(十)

常用特性應用場景1 過濾器
Vue.filter 定義一個全局過濾器
[mw_shl_code=applescript,true] <tr :key='item.id' v-for='item in books'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<!-- 1.3 調用過濾器 -->
<td>{{item.date | format('yyyy-MM-dd hh:mm:ss')}}</td>
<td>
<a href="" @click.prevent='toEdit(item.id)'>修改</a>
<span>|</span>
<a href="" @click.prevent='deleteBook(item.id)'>刪除</a>
</td>
</tr>

<script>
#1.1 Vue.filter 定義一個全局過濾器
Vue.filter('format', function(value, arg) {
function dateFormat(date, format) {
if (typeof date === "string") {
var mts = date.match(/(\/Date((\d+))\/)/);
if (mts && mts.length >= 3) {
date = parseInt(mts[2]);
}
}
date = new Date(date);
if (!date || date.toUTCString() == "Invalid Date") {
return "";
}
var map = {
"M": date.getMonth() + 1, //月份
"d": date.getDate(), //日
"h": date.getHours(), //小時
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
"q": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
var v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
}
return dateFormat(value, arg);
})
#1.2 提供的數據 包含一個時間戳 爲毫秒數
[{
id: 1,
name: '三國演義',
date: 2525609975000
},{
id: 2,
name: '水滸傳',
date: 2525609975000
},{
id: 3,
name: '紅樓夢',
date: 2525609975000
},{
id: 4,
name: '西遊記',
date: 2525609975000
}];
</script>[/mw_shl_code]
2 自定義指令
讓表單自動獲取焦點
通過Vue.directive 自定義指定
[mw_shl_code=applescript,true]<!-- 2.2 通過v-自定義屬性名 調用自定義指令 -->
<input type="text" id="id" v-model='id' :disabled="flag" v-focus>

<script>

2.1 通過Vue.directive 自定義指定

    Vue.directive('focus', {
  inserted: function (el) {
    el.focus();
  }
});

</script>[/mw_shl_code]
3 計算屬性
通過計算屬性計算圖書的總數
圖書的總數就是計算數組的長度
[mw_shl_code=applescript,true]<div class="total">
<span>圖書總數:</span>
<!-- 3.2 在頁面上 展示出來 -->
<span>{{total}}</span>
</div>

<script type="text/javascript">
/
計算屬性與方法的區別:計算屬性是基於依賴進行緩存的,而方法不緩存
/
var vm = new Vue({
data: {
flag: false,
submitFlag: false,
id: '',
name: '',
books: []
},
computed: {
total: function(){
// 3.1 計算圖書的總數
return this.books.length;
}
},
});
</script>[/mw_shl_code]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章