Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 491
Sadeghbayan Avatar asked Oct 27 '25 16:10

Sadeghbayan


2 Answers

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>

like image 194
Bennett Dams Avatar answered Oct 30 '25 07:10

Bennett Dams


Just assigned the imported function to a data property like below

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

Then in the data section;

data(){
    return {
      convertToSome: convertToSome
    }
}
like image 20
YKalinde Avatar answered Oct 30 '25 07:10

YKalinde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!