Author: Ed Zynda
Translator: Front-end wit
Source:scotch.io
Look after it and get used to it
This article GitHub https://github.com/qq44924588... I've included more categories of articles I've praised in the past, and I've also sorted out a lot of my documents and tutorial materials.Welcome to Star and Perfection. You can review the interview with reference points. I hope we have something together.
Similar to Angular JS,Vue.js There are also their own data conversion and filtering methods, but it is important to remember that filters do not change the original data; they only change the output and return the filtered data.Filters are useful in many different situations, such as keeping the API response as clean as possible and working with data formats on the front end.They are also very effective in situations where you want to avoid duplication and connections by encapsulating all the logic behind reusable blocks of code.
Define and use filters
With Vue, we can register filters in two different ways: global and local.The former provides access to filters in all components, while the latter can only use filters within the components that define the component.
Filters are simple JS functions that take the value to be converted as the first parameter, but can also pass in as many other parameters as possible to return a formatted version of the value.
Global filter
The global filters are as follows:
// In this example, we will register a global filter to add a dollar sign before the price: // statement Vue.filter('toUSD', function (value)) { return `$${value}` } // Use <div id="app"> <span>{{ 351.99 | toUSD }}</span> </div>
The filter definition must always be above the main Vue instance, or you will get a Failed to resolve filter: toUSD error.
// DECLARATION Vue.filter('toUSD', function (value) { return `$${value}`; }); new Vue({ el: '#app', data: { price: 351.99 } }); // USAGE <div id="app"> <span>{{ price | toUSD }}</span> </div>
Local filter
Local filters are registered in a Vue component scope to see how they are created:
// In this example, we will create a filter that capitalizes the string. // statement new Vue({ el: '#app', data: { name: 'scotch.io' }, filters: { // Filter definitions Upper(value) { return value.toUpperCase(); } } }); // usage <div id="app"> <span>{{ name | Upper }}</span> </div>
As you can see in the example above, local filters are stored in the Vue component as functions within the "filters" property.We can register any number of:
... filters: { Upper(value) { return value.toUpperCase(); }, Lower(value) { return value. toLowerCase(); }, } ....
Additional parameter settings
As mentioned in the introduction to this article, filters can accept as many parameters as needed
// statement Vue.filter('readMore', function (text, length, suffix) { return text.substring(0, length) + suffix; }); new Vue({ el: '#app', data: { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non ab modi repellendus labore facere, fugiat ipsam quae accusantium commodi voluptas nesciunt dolor similique ipsum accusamus earum eligendi suscipit laborum quod.' } }); // usage <div id="app"> <span>{{ text | readMore(10, '...') }}</span> </div>
In this example, we create a filter named "readMore" that limits the length of a string to a given number of characters and adds the suffix of your choice to it.Vue.js The filtered values are passed as the first parameter, text, and length and suffix as the second and third parameters.
Chain filter
My favorite thing about filters is the ability to link them using pipe (|) symbols and run individual values through a series of converters.To take another example of price, we want to limit the decimal places of the price and the units for which the price is increased.
// JS Vue.filter('toFixed', function (price, limit) { return price.toFixed(limit); }); Vue.filter('toUSD', function (price) { return `$${price}`; }); new Vue({ el: '#app', data: { price: 435.333 } }); // HTML <div id="app"> <span>{{ price | toFixed(2) | toUSD }}</span> </div>
Example
Next, we'll consolidate through a few examples.
Convert JS values to JSON strings
// JS Vue.filter('json', function (value) { return JSON.stringify(value); }); new Vue({ el: '#app', data: { user: { username: 'johndoe', email: 'john@example.com', countryCode: 'U.K.' } } }); // HTML <div id="app"> <span>{{ user | json }}</span> </div>
Extracting a list of attribute values from an array of objects
Vue.filter('pluck', function (objects, key) { return objects.map(function(object) { return object[key]; }); }); new Vue({ el: '#app', data: { users: [ { "id": 4, "first_name": "Eve", "last_name": "Holt" }, { "id": 5, "first_name": "Charles", "last_name": "Morris" }, { "id": 6, "first_name": "Tracey", "last_name": "Ramos" } ] } }); // HTML <div id="app"> <span>{{ users | pluck('last_name') }}</span> </div>
Returns the element at the given index
Vue.filter('at', function (value, index) { return value[index]; }); new Vue({ el: '#app', data: { videos: ['Zi_XLOBDo_Y', 'sOnqjkJTMaA', 'sOnqjkJTMaA'] } }); // HTML <div id="app"> <span>{{ videos | at(1) }}</span> </div>
Returns the minimum value in a given list
// JS Vue.filter('min', function (values) { return Math.min(...values); }); new Vue({ el: '#app', data: { ages: [23, 19, 45, 12, 32] } }); // HTML <div id="app"> <span>{{ ages | min }}</span> </div>
Randomly arranged list of elements:
Vue.filter('shuffle', function (values) { for (var i = values.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = values[i]; values[i] = values[j]; values[j] = temp; } return values; }); new Vue({ el: '#app', data: { cards: ['Lahire', 'Judith', 'Lancelot', 'Alexandre'] } }); // HTML <div id="app"> <span>{{ cards | shuffle }}</span> </div>
Returns the first element of the array:
Vue.filter('first', function (values) { if(Array.isArray(values)) { return values[0]; } return values; }); new Vue({ el: '#app', data: { consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari'] } }); // HTML <div id="app"> <span>{{ consoles | first }}</span> </div>
Returns the last element of the array
Vue.filter('last', function (values) { if(Array.isArray(values)) { return values[values.length - 1]; } return values; }); new Vue({ el: '#app', data: { consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari'] } }); // HTML <div id="app"> <span>{{ consoles | last }}</span> </div>
Returns a copy of the array that filters the specified elements
Vue.filter('without', function (values, exclude) { return values.filter(function(element) { return !exclude.includes(element); }); }); new Vue({ el: '#app', data: { unpaidInvoices: ['#1001', '#1002', '#1003', '#1004'] } }); // HTML <div id="app"> <span>{{ unpaidInvoices | without('#1003') }}</span> </div>
Remove duplicate elements from the array
Vue.filter('unique', function (values, unique) { return values.filter(function(element, index, self) { return index == self.indexOf(element); }); }); new Vue({ el: '#app', data: { recentViewedPosts: [13, 43, 23, 13, 43, 3, 98, 42, 65] } }); // HTML <div id="app"> <span>{{ recentViewedPosts | unique }}</span> </div>
Add text after the string
Vue.filter('prepend', function (string, prepend) { return `${string}${prepend}`; }); new Vue({ el: '#app', data: { greeting: 'Hello' } }); // HTML <div id="app"> <span>{{ greeting | prepend(' World!') }}</span> </div>
Repeat a string n times
Vue.filter('repeat', function (string, times) { return string.repeat(times); }); new Vue({ el: '#app', data: { greeting: 'Hello' } }); // HTML <div id="app"> <span>{{ greeting | repeat(3) }}</span> </div>
summary
Hopefully readers will learn something from this article. Now you know how to create and use filters. Most importantly, you can now refactor your code and clean it up with filters.
BUGs that may exist after code deployment are not known in real time. In order to solve these BUGs afterwards, a lot of time has been spent debugging the log. By the way, a useful BUG monitoring tool is recommended. Fundebug.
Original: https://scotch.io/tutorials/g...
Communication
The article is continuously updated every week, so WeChat can search for "The Big Move World" for the first time to read and hurry up (one or two earlier than the blog), GitHub https://github.com/qq449245884/xiaozhi I have included, sorted out a lot of my documents, welcome to Star and perfect, you can refer to the reference point for review, and pay attention to the public number, the background reply benefits, you can see benefits, you understand.