过滤器:让要显示在页面上的内容进行重新筛选
全局过滤器:
语法: Vue.filter('过滤器的名字',function(){
})
例子:
<div id='itany'>
<p>{{new Date()|date}}</p>
</div>
<script src='js/vue.js'></script>
<script>
Vue.filter("date",function(data){
return data.getFullYear()+'年'+(data.getMonth()+1)+'月'+data.getDate()+'日,星期'+data.getDay()+','+data.getHours()+'点'+data.getMinutes()+'分'+data.getSeconds()+'秒';
})
new Vue({
el:'#itany'
})
</script>
局部过滤器:
语法:new Vue({
el:''
data:{}
methods:{},
filters:{
过滤器名:function(data){
}
})
例子:
<div id='itany'>
<p>{{123.41233|number}}</p>
</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#itany',
filters:{
number:function(data){
return data.toFixed(2)
}
}
})
</script>
计算属性实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='itany'>
<button @click='add'>加货</button>
<h1>{{total}}</h1>
</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#itany',
data:{
package1:{price:2,count:3},
package2:{price:4,count:6}
},
computed:{
total:function(){
return this.package1.price*this.package1.count+this.package2.price*this.package2.count
}
},
methods:{
add:function(){
this.package1.count++;
}
}
})
</script>
</body>
</html>
运行结果:时间过滤实例:
全局过滤器:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='itany'>
<p>{{new Date()|date}}</p>
</div>
<script src='js/vue.js'></script>
<script>
Vue.filter("date",function(data){
return data.getFullYear()+'年'+(data.getMonth()+1)+'月'+data.getDate()+'日,星期'+data.getDay()+','+data.getHours()+'点'+data.getMinutes()+'分'+data.getSeconds()+'秒';
})
new Vue({
el:'#itany'
})
</script>
</body>
</html>
运行结果:
局部过滤器:保留小数点后两位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='itany'>
<p>{{123.41233|number}}</p>
</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#itany',
filters:{
number:function(data){
return data.toFixed(2)
}
}
})
</script>
</body>
</html>
运行结果: