简体   繁体   中英

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 ?

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>

Just assigned the imported function to a data property like below

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

Then in the data section;

data(){
    return {
      convertToSome: convertToSome
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM