There is probably no doubt about the use of filters. There is a very detailed explanation on vue.js website, which will not be described here.
And want to use global filter in methos, actually is simply lazy, initially only in the dom format data, which thought that also has a part in js data (especially echarts data) need to format, don’t want to filter into public methods, after all this, all the page has to be quoted again, it is trouble.
Try and dom, using |, not much said, indeed as expected failure; $options. Filters [key] () {this.$options. Filters [key] () {this.$options. Filters [key] ¶ This.$options.filters[key] retrieves only the registered filters for the current page, not the global filters. It is vue2. X itself that limits this of filter, and methods are recommended by the authorities.
However, my current situation is that I only need to change one or two places. In the existing project, it is too much work to change all the pages for a small place.
Finally, after repeatedly looking up information (BAI) material (DU), this thought of a method. The DOM still uses filters to format data, but when there is a global filter that JS needs to use, methods are introduced and methos is used.
The code is as follows:
- Create a filter.js file to hold all the filter methods and export each method using export
Export let numberdata => {if(data){return data.tolocaleString ()}else{return data}} // String in uppercase export let stringUpperCase = value=> { if (! value) return '' value = value.toString() return value.toUpperCase() }Copy the code
- Register global filters in main.js
import * as filters from './common/filter'
Object.keys(filters).forEach(key => {
Vue.filter(key,filters[key])
})
Copy the code
- Use in pages
<template>
<div>
<p>Using a global filter: {{10000 | numberUnify}}</p>
<p>Using the current component filters: {{' jack '| capitalize}}</p>
<p>{{localFilter}}</p>
<p>{{globalFilter}}</p>
<p>Used to introduce global filter: {{' jump '| stringUpperCase}}</p>
</div>
</template>
<script>
import { stringUpperCase } from '@/common/filter'
export default {
data(){
return{
globalFilter: "".localFilter: ""}},filters: {
capitalize: function (value) {
if(! value)return ' '
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)}},created(){
this.globalFilter = stringUpperCase('globalFilter') // Global filter calls method
this.localFilter = this.$options.filters['capitalize'] ('localFilter') // The current local filter calls the method}}</script>
Copy the code
This way, you can use the same method in THE DOM as well as in JS, with no major changes required. Dom display content: