Vue中的自定义指令和过滤器

一.自定义指令

1.全局自定义(无参数)

效果:实现h2标签内的标题刷新后随机更换颜色.

步骤:在main.js中先使用vue自定义指令,如第二章图中,设置一个名称,然后设置指令想要实现的效果;然后给需要的标签绑定指令,就可以达到效果了。

<h2 v-rainbow>{{blog.title}}</h2>
//全局:在main.js中自定义
//第一个参数为要定义的指令名称,第二个参数为绑定内容
Vue.directive('rainbow',{
	bind(el,binding,vnode){
 		el.style.color = '#' + Math.random().toString(16).slice(2,8);     //修改绑定元素的颜色
    }
})

2.全局自定义(有参数)

效果:根据绑定参数修改内容宽度.

步骤:同样,在main.js中先自定义指令进行设置达到的效果,然后给标签绑定指令即可。和无参数的区别   就是可以根据所给参数以及绑定的值进行判断,分情况对待,更好满足需求。

//特别注意:这里wide是字符串,不加单引号不正确
<div id="show-blog" v-theme:column="'wide'">    
    <h1>博客总览</h1>
    <div class="single-blog" v-for="blog in blogs">
      <h2 v-rainbow>{{blog.title}}</h2>
      <article>{{blog.body}}</article>
    </div>
</div>
//指令名称为theme,如果给定参数是column设置背景色和padding,如果绑定的值为wide最大宽度为1260px,如果为narrow为560px
Vue.directive('theme',{
	bind(el,binding,vnode){
		if(binding.value == 'wide'){
			el.style.maxWidth = '1260px';
		}else if(binding.value == 'narrow'){
			el.style.maxWidth = '560px';
		}

		if(binding.arg == 'column'){
			el.style.background = '#6677cc';
			el.style.padding = '20px';
		}
	}
})

3.局部自定义

直接在需要的子组件内定义并使用,代码如下,需要和name,data等同级,给定directives,然后设置就好了。

 name: 'show-blog',
 data(){
    return {
      blogs:[],
      search:''
    }
  },
  directives:{
    'rainbow':{
      bind(el,binding,vnode){
        el.style.color='#' + Math.random().toString(16).slice(2,8);;
      }
    }
  }

二.自定义过滤器

1.过滤器

效果:实现搜索功能,匹配标题中含有的关键字展示出来.

<div id="show-blog" v-theme:column="'wide'">    
    <h1>博客总览</h1>
    <input type="text" v-model="search" placeholder="搜索">
    <div class="single-blog" v-for="blog in filteredBlogs">
      <h2 v-rainbow>{{blog.title}}</h2>
      <article>{{blog.body}}</article>
    </div>
</div>

export default {
  name: 'show-blog',
  data(){
    return {
      blogs:[],
      search:''
    }
  },
  computed:{
    filteredBlogs:function(){
      return this.blogs.filter((blog)=>{
        return blog.title.match(this.search);
      })
    }
  }
}

代码如上,给搜索框绑定一个search,将输入的东西进行和博客内容进行匹配,匹配的博客放在computed中,返回和输入内容匹配的标题的blog,此时遍历时blog in fiteredBlogs,遍历处理过的blogs.

2.全局自定义过滤器

效果:所有博客标题大写

步骤:依然是在main.js中进行自定义,使用filter过滤器,第一个参数是要使用的名称,第二个参数是回调    函数,参数value用来接收传来的title,调用toUpperCase方法将其转换为大写。然后给标签绑定过滤器。

Vue.filter("to-uppercase",function(value){
   return value.toUpperCase();         //value接收title
})
<h2 v-rainbow>{{blog.title | to-uppercase}}</h2>

3.局部自定义过滤器

效果:同上

步骤:在子组件中直接写入filters进行设置,如下是两种方法,第一种比较常见。需要注意的是第一种方法   标签中使用时需要写to-uppercase,而第二种方法需要写toUpperCase.如果有多个过滤器,以逗号隔开,后面跟着写就可以了。

filters:{
    //第一种方法
    "to-uppercase":function(value){
      return value.toUpperCase();
    }
    //第二种方法
    // toUpperCase(value){
    //   return value.toUpperCase();
    // }
}

猜你喜欢

转载自my.oschina.net/GracefulTing/blog/1796844