过滤器使用
一、何处定义过滤器
在Vue实例中定义过滤器
<script type='text/javascript'>
const app = new Vue({
el:'#app',
// 定义数据
data:{
},
// 定义方法
methods:{
},
// 定义计算属性
computed:{
},
// 定义过滤器
filters:{
过滤器名称:function(value){
}
}
})
</script>
在创建Vue实例之前定义过滤器
Vue.filter('过滤器名称', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
new Vue({
// ...
})
二、过滤器的作用
对所要展示的数据进行筛选处理,并不会改变原有数据
三、过滤器的使用
<!-- 在双花括号中 -->
{{ message | 过滤器 }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | 过滤器"></div>
四、注意
- 当全局过滤器和局部过滤器重名时,会采用局部过滤器。
- 过滤器函数总接收表达式的值 (之前的操作链的结果) 作为第一个参数。在下例中, 过滤器函数将会收到 message 的值作为第一个参数。并且过滤器还可以串联
{{ message | filterA | filterB }}
在这个例子中,filterA 被定义为接收单个参数的过滤器函数,表达式 message 的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数 filterB,将 filterA 的结果传递到 filterB 中。
- 过滤器是 JavaScript 函数,因此可以接收参数:
{{ message | filterA('arg1', arg2) }}
这里,filterA 被定义为接收三个参数的过滤器函数。其中 message 的值作为第一个参数,普通字符串 ‘arg1’ 作为第二个参数,表达式 arg2 的值作为第三个参数。
五、案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type='text/javascript' src='js/vue.js'></script>
<style type='text/css'>
table{
border: 1px solid #ccc;
border-collapse: collapse;
border-spacing: 0;
}
th{
background-color: #eee;
}
th , td{
padding: 8px 16px;
border: 1px solid #ccc;
text-align: left;
}
</style>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item , index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.Bdata}}</td>
<!-- 过滤器的使用 -->
<td>{{item.price | getTotal}}</td>
<td>
<button @click="decrement(index)">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="removeClick(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<!-- 过滤器的使用 -->
<h2>总价格:{{totalPrice | getTotal}}</h2>
</div>
<script type='text/javascript'>
const app = new Vue({
el:'#app',
data:{
books:[
{
id:1,
name:'算法导论',
Bdata:'2012-3',
price:67,
count:1,
},
{
id:2,
name:'java学习',
Bdata:'2014-5',
price:57,
count:1,
},
{
id:3,
name:'C++基础',
Bdata:'2011-3',
price:60,
count:1,
},
{
id:4,
name:'python学习',
Bdata:'2012-3',
price:97,
count:1,
}
],
},
computed:{
totalPrice(){
let total = 0;
for(let i=0 ; i<this.books.length ; i++){
total += this.books[i].count * this.books[i].price
}
return total
}
},
methods:{
increment(index){
this.books[index].count++
},
decrement(index){
this.books[index].count--
},
removeClick(index){
this.books.splice(index , 1)
}
},
filters:{
// 定义过滤器
getTotal(price){
// 该过滤器作用是保留两位小数以及在加个前面加¥
return '¥' + price.toFixed(2);
}
}
})
</script>
</body>
</html>