Error creating global Filters with vuejs

Asked

Viewed 102 times

0

I am trying to create some filters globally in vuejs but am getting error "Failed to resolve filter".

My main.js is like this

import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

Vue.filter("teste", function(value){
        return "OK";
})

2 answers

0

You probably missed importing the desired filter. What I advise to do in case of a global filter:

  1. Create a separate js file, in a Filters folder for example. Each file will be a filter, example under a simple filter:

name-substr-format.js

export function nameSubstrFormat (name, number = 33) {
  if (name) {
    return name.substring(0, number)
  }

  return ''
}

The above filter is a file that exports only one function, in which case its functionality is to limit the amount of characters in a string. If nothing passes, returns 33 characters at most.

  1. Now import it into your main.js and call him in his instance Vue:

import { nameSubstrFormat } from './filters/name-substr-format' Vue.filter('nameSubstrFormat', nameSubstrFormat)

  1. To use it directly in your HTML, just call it within an interpolation, after the pipe ("|"), the first parameter becomes the interpolation variable.

<span>{{ nome | nameSubstrFormat(20) }}</span>

Note that it can be used both with variables within your data(), how many computed variables (computed properties).

0

Your script seems to be right it seems that the problem is in the component, try so:

Vue.filter('teste', function(value) {
   if (value) {
      return 'ok'
   }
})

<template>
   <div>
     {{ var | teste }}
   </div>
</template>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.