Vue filter of Vue plug-in
What is a filter?
Let's take Li ziha for example: the user has entered an English sentence, we need to capitalize the first letter. Before displaying this sentence, we need to add a filter to make the sentence capitalized
Another Chestnut: you request data and get an array. When rendering, you need to convert the array into a key object. Before rendering, use the filter to process the array
As can be seen from the two chestnuts above, the filter is to do some special processing for the target data before data rendering or use, so as to facilitate subsequent rendering or use
How is the filter implemented?
-
Common filter
// A normal filter is usually a function method let fliterA = (str) => { if (!str) return '' str = str.toString() return str.charAt(0).toUpperCase() + str.slice(1) } // The call is also very simple, that is to call the method of fliterA(str) fliterA('abc') // Back: Abc
Filters in Vue: ordinary filters look ugly and have poor scalability, so there is a fliter object in Vue that is specially used to construct filters. Fliter objects can be placed in a Vue build to declare a local filter, or in a single js file to declare a global Vue filter. They are used exactly the same way in components.
-
Local filter
<!-- test.vue --> <template> <span> {{ 'abc' | fliterA }} </span> </template> <script> export default { data() { return {} }, filters: { fliterA: (str) => { if (!str) return '' str = str.toString() return str.charAt(0).toUpperCase() + str.slice(1) } } } </script> <!-- The result of page rendering is: Abc -->
-
Global filter
// fliter.js import Vue from 'vue' /** * @interface fliterA {str} */ Vue.filter('fliterA', (str) => { if (!str) return '' str = str.toString() return str.charAt(0).toUpperCase() + str.slice(1) })
-
Use in components
<template> <span>{{ 'hello ' | fliterA }}</span> </template>