<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--<script src="https://cdn.bootcss.com/vue/2.5.22/vue.min.js"></script>-->
<script src="lib/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>{{msg | textFilter|textFormat("欧巴")}}</p>
<p>{{msg|dataFormat}}</p>
<p v-color="'blue'">{{msg}}</p>
<p v-fontweight="900" v-bgColor="'blue'">{{msg}}</p>
</div>
<script>
/*
vue自定义过滤器
可用作一些常见文本的格式化
可用在两个地方:差值表达式和v-bind
过滤器应该添加在js表达式的尾部,由管道符指示
Vue.filter('过滤器名称',function(data){})
data:需要过滤的数据
注意:过滤器放在vue实例的后面不起作用,过滤器不对原数据产生影响
*/
//全局过滤器
Vue.filter('textFilter',function(msg){
// replace 第一个参数除了写一个字符串之外,还可以写一个正则
// replace('呵呵','哈哈')只会替换第一个
return msg.replace(/呵呵/g,'哈哈');
});
Vue.filter('textFormat',function(msg,arg){
return msg.replace(/哈哈/g,arg);
});
//全局指令
Vue.directive('color',{
bind:function(el,binding){
el.style.color=binding.value;
},
inserted:function(el){
}
});
var app = new Vue({
el:"#app",
data:function(){
return {
msg:"呵呵,蛟龙,呵呵,你好!"
}
},
methods:{},
filters:{//定义私有过滤器
/*如果全局过滤器和私有过滤器重名,优先调用私有过滤器*/
'dataFormat':function(data){
return data.replace(/呵呵/g,"喵喵");
}
},
//局部指令
directives:{
'fontweight':{
bind:function(el,binding){//绑定样式
el.style.fontWeight=binding.value;
},
inserted:function(){//绑定事件
}
},
//在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。可以这样写
'bgColor':function(el,binding){
el.style.backgroundColor = binding.value;
}
}
});
</script>
</body>
</html>
vue-过滤器和指令
最新推荐文章于 2023-10-18 15:31:24 发布