Vue中自定义过滤器
2018-11-04 本文已影响2人
___大鱼___
导入Vue.js后直接在script中定义 {{ msg | msgFormat }}
同样Vue过滤器名字中可以传参, 可以替换成你想要的参数
{{ msg | msgFormat('神秘') }}
Vue.filter(msgFormat, function(msg, arg){
return msg.replace(/大哥/g, arg)
})
Vue.filter('过滤器的名字', function(msg){
})
自定义替换字符串大哥为哈哈哈的过滤器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<body>
<div id="name">
{{msg | msgFormat}}
</div>
</body>
<script>
Vue.filter('msgFormat', function (msg) {
// 正则表达式替换, 否则replace只能替换一个大哥
return msg.replace(/大哥/g, '哈哈哈')
});
var app1 = new Vue({
el: '#name',
data:{
msg: '曾经我是你大哥, 后来我编程了你大哥, 可是你不知道我是你大哥, 希望我是你大哥!'
},
methods: {
}
})
</script>
</html>