The filter is to further screen the data to be displayed, and then display it. It is worth noting that the filter does not change the original data, but only generates new data based on the original data. Filters are divided into global filters and local filters (local filters).
Table of contents
global filter
<div id="app">
{
{message | toAdd}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.filter("toAdd", function(value) {
return 'VUE' + value
})
var demo = new Vue({
el: '#app',
data: {
message: '过滤器',
}
})
</script>
local filter
<div id="app">
<p>{
{message | Reverse}}</p>
<p>{
{message | Length}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var demo = new Vue({
el: '#app',
data: {
message: '过滤器',
},
filters: {
Reverse: function(value) {
if (!value){
return '';
}
return value.toString().split('').reverse().join('');
},
Length: function(value) {
return value.length;
},
},
})
</script>
The first p tag splits the obtained msg data, flips the split characters, and finally outputs them. The second p tag obtains the length of the data obtained and displays it. The result of the operation is as follows:
filter parameter
In addition, filters can also pass parameters.
<div id="app">
{
{msg1 | toDou(1,2)}}
{
{msg2 | toDou(10,20)}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.filter('toDou', function(value, param1, param2) {
if (param2 < 10) {
return value + param1;
} else {
return value + param2;
}
});
new Vue({
el: '#app',
data: {
msg1: 9,
msg2: 12,
}
});
</script>
inline filter
<div id="app">
{
{money | prefix | suffix}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.filter("prefix", function(value) {
return '¥' + value
})
Vue.filter("suffix", function(value) {
return value + '元'
})
var demo = new Vue({
el: '#app',
data: {
money:10
}
})
</script>
The above code mainly adds two filters to the value in the interpolation expression at the same time. Money will be processed by the prefix filter first, and the processed value will be processed by the suffix filter. The corresponding code operation effect is as follows: