Base
Similar to a custom directive, a custom filter can be registered with the global method Vue.filter(), which takes two parameters: the filter ID and the filter function. The filter function takes the value as a parameter and returns the converted value:
Vue.filter('reverse', function (value) { return value.split('').reverse().join('')})<!-- 'abc' => 'cba' --><span v-text="message | reverse"></span>
The filter function can receive any number of parameters:
Vue.filter('wrap', function (value, begin, end) { return begin + value + end})<!-- 'hello' => 'before hello after' --><span v-text="message | wrap 'before' 'after'"></span>
Bidirectional filter
Currently we use filters to convert the value from the model before displaying it in the view. However, it is also possible to define a filter that converts the value from the view (<input> element) before writing it back to the model:
Vue.filter('currencyDisplay', { // model -> view // Format the value before updating the `<input>` element read: function(val) { return '$'+val.toFixed(2) }, // view -> model // Format the value before writing back the data write: function(val, oldVal) { var number = +val.replace(/[^/d.]/g, '') return isNaN(number) ? 0 : parseFloat(number.toFixed(2)) }})Dynamic parameters
If the filter parameter is not wrapped in quotes, it will be calculated dynamically within the current vm scope. Also, this of the filter function always points to the vm that calls it. For example:
<input v-model="userInput"><span>{{msg | concat userInput}}</span> Vue.filter('concat', function (value, input) { // `input` === `this.userInput` return value + input})The above example is relatively simple, and you can also use expressions to achieve the same result, but for more complex logic, more than one statement is required, and you need to put it in a computed property or a custom filter.
Built-in filters filterBy and orderBy filter/sort incoming arrays based on the current state of the Vue instance to which it belongs.
This article has been compiled into the "Vue.js Front-end Component Learning Tutorial", and everyone is welcome to learn and read.
For tutorials on vue.js components, please click on the special topic vue.js component learning tutorial to learn.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.