⑴ 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
}
}
}
})