如何在vuejs .vue模板中为导入的模块使用辅助函数?

时间:2017-02-09 18:56:09

标签: vuejs2

我有一个包含的helper.js文件:

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

我的.vue文件有:

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

我收到以下错误:

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.

2 个答案:

答案 0 :(得分:1)

在你的vue组件中创建新的帮助器实例,如下所示。

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

答案 1 :(得分:0)

我认为您需要为导入值创建“数据值”。你可以尝试这样的事情:

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