⑴ vue如何自定義過濾器
一、什麼是過濾器?
過濾器是在數據渲染時,根據使用的過濾器來渲染數據,過濾器不改變真正的data,而只是改變渲染的結果,並返回過濾後的版本。
二、過濾器怎樣使用?
渲染時使用 「| 過濾器名稱」。eg: v-for=」val in arr | filterBy 『a』 取包含』a』的數據
三、常用過濾器介紹
1、debounce ------配合事件,延遲執行
eg: @keyup=」functionname | debounce 2000 」
2、limitBy 配合數據,限制幾條數據
eg: v-for=」val in arr | limityBy 2 1」 從下標為1的元素開始取兩條數據
eg: v-for=」val in arr | limityBy 2」 只取前2條數據
3、filterBy 取包含某個元素的數據
eg: v-for=」val in arr | filterBy 『a』 取包含』a』的數據
4、orderBy 1(升序)/2(降序)排序
eg: v-for="val in arr | orderBy 1" 升序排序
eg: orderBy 年齡 1 按年齡升序排序
三、自定義過濾器
時間過濾器
<div class="box">
⑵ Vue的組件,過濾器,自定義指令以及v-if
<div class="app">
<h1 v-show="false">我愛你</h1>
v-if是直接將dom刪除了,在dom文檔中已經找不到對應的dom,變成了注釋
<h1 v-if="false">我愛你</h1>迅改
如果頻繁使用 就使用v-show 可以節約性能開銷
如果短暫使用,例如頁面一開始載入的時候進行判斷顯示 優先使用v-if
實際開發中,使用v-if比較多
<li v-for="(item,index) in arr">{{item}}</li>
</div>
<script src="./node_moles/vue/dist/vue.js"></script>
<script>
new Vue({
el: '.app',
data: {
畝察判 msg: 123,
list: [1, 2, 3]
},
computed: {
arr: function () {
return this.list.filter(r => r > 1)
}
},
methods: {
}
})
</script>
<div class="app">
<child1></child1>
<div><child-a/></div>
<div><child-b/></div>
<template id="childB">
<div>
<h1>我是程序員</h1>
<h1>我是程序員</h1>
</div>
</template>
</div>
<script src="./node_moles/vue/dist/vue.min.js"></script>
<script>
Vue.component('child1',{
template:`<h1>我是child1</h1>`
})
Vue.component('childA',{
template:`<h1>我是childA</h1>`
})
Vue.component('childB',{
template:'#childB'
})
new Vue({
el:'.app'
})
</script>
<div class="app" v-cloak>
<h1>{{'我愛張sir'|str('金牌廚師')}}</h1>
<h1>{{'hello'|he}}</h1>
</div>
<script src="./node_moles/vue/dist/vue.js"></script>
<script>
Vue.filter('fn',function(v,s){
console.log(v);
return v/* .substring(0,v.indexOf(':')) */+s
})
new Vue({
el:'.app',
/* 局部過濾器 */
filters:{
str(v,s){
return v+s
},
he(v){
return v.split('').reverse().join('')
}
}
})
當頁面刷新的時候data中的數據還沒有渲染出來,頁面中就會顯示原本寫的插值語法,這時候就需要消除這個bug
在綁定的實例化對象的元素上上添加v-cloak 並在style樣式中添加(只要前面加上v-都可以實沒談現,隨意命名,通常使用clock)
display: none;
}
<div class="app">
<input type="text" v-bg>
<input type="text" v-focus="{background:'yellow'}">
<div style="width: 100px;height: 100px;" v-bg></div>
<p v-sty="{background:'pink',color:'yellow'}">我是程序員</p>
</div>
<script src="./node_moles/vue/dist/vue.js"></script>
<script>
Vue.directive('bg', function (el) {
/* 回調的第一個參數就是元素本身 */
console.log(el);
el.style.background = 'red'
})
/* 全局自定義指令 寫全方式 */
Vue.directive('focus', {
/* 當綁定元素插入到DOM中 */
inserted: function (el, bind) {
el.focus();
console.log(bind);
el.style.background = bind.value.background
}
})
new Vue({
el: '.app',
/* 局部的自定義指令 要加s */
directives: {
sty: {
inserted (el, bind) {
el.style.background = bind.value.background;
el.style.color = bind.value.color
}
}
}
})