Sadeghbayan
Sadeghbayan

Reputation: 1163

Calling a function from a helper in Vue Template

In my Helper function I have ConvertToSome Function:

export function convertToSome(item) {
  item = item.toString();
  var qq = "qwqe";
  for(var i=0;i<10;i++)
  {
    item = item.split(i).join(qq[i]);
  }
  return item;
}

And In my Vue I have Component like this :

import { convertToSome } from '../../../helpers';

when I want to use this function in component I got this error :

TypeError: "_vm.convertToSome is not a function"

How can I use this function into template ?

Upvotes: 4

Views: 6957

Answers (2)

YKalinde
YKalinde

Reputation: 156

Just assigned the imported function to a data property like below

import { convertToSome } from '../../../helpers'; 

Then in the data section;

data(){
    return {
      convertToSome: convertToSome
    }
}

Upvotes: 4

Bennett Dams
Bennett Dams

Reputation: 7033

With your import statement (import { convertToSome } from '../../../helpers';) you could create a local method in your Vue instance and use the imported function inside:

  methods: {
    convertToSome(item) {
      // "convertToSome" inside is the imported function
      return convertToSome(item);
    }
  }

You can call this.convertToSome(item) anywhere in your script to call the Vue method which will use the imported function.

...or directly in your template:

<div> {{ convertToSome(item) }} <div>

You could also use the imported function as a filter (as proposed by @thanksd), which seems more suitable in your case:

  filters: {
    convertToSome(item) {
      return convertToSome(item);
    }
  },

...which you could use directly in your template:

<div> {{ foo | convertToSome }} <div>

Upvotes: 10

Related Questions