Raine
Raine

Reputation: 117

How to use helper functions for imported modules in vuejs .vue template?

I have a helper.js file with contains:

module.exports = {
    getSrmColor: (color) => {
        return color;
    }
}

My .vue file has:

<template>
    <div>
    {{ recipeHelper.getSrmColor(recipe.color) }}
    </div>
</template>
<script>
    import recipeHelper from "./helpers.js";
    export default {
        name: "Recipe",
        props: ["recipe"]
    }
</script>

I get the following error:

Property or method "recipeHelper" is not defined on the instance but referenced during render. 
Make sure to declare reactive data properties in the data option.

Upvotes: 3

Views: 1628

Answers (2)

Hax0r
Hax0r

Reputation: 1803

Make new helper instance inside your vue component, like below.

<script>
import recipeHelper from "./helpers.js";
export default {
  name: "Recipe",
  props: [
    "recipe"
  ],
  mounted: function() {
    this.recipeHelper = recipeHelper;
  }
}
</script>

Upvotes: 3

Dmitry Kurmanov
Dmitry Kurmanov

Reputation: 775

I think you need to create "data value" for your import value. Could you try something like that:

<script>
 import recipeHelper from "./helpers.js";
 export default {
     name: "Recipe",
     props: ["recipe"],
     data: function() {return {
          recipeHelper: recipeHelper
     }}
 }
</script>

Upvotes: 1

Related Questions