如何在模板中导入函数?

时间:2017-11-12 18:30:04

标签: javascript vue.js

我目前遇到的问题是渲染期间未引用导入的函数。这段代码更容易解​​释:

<template>
<div v-for="(addOn, index) in JSON.parse(this.restaurants[0].categories[categoryId].addons)">
    <label>
        <span>{{ addOn.name }} (+ ${{ addZeroes(addOn.price) }})</span>
    </label>
</div>
</template>

<script>
    import { addZeroes } from "../../../js/helpers";

    export default {
        data() {
            return {
                // populated via AJAX
                restaurants: [
                    {
                        categories: []
                    }
                ],
            }
        },

    }
</script>

<style>
</style>

,错误是:

[Vue warn]: Property or method "addZeroes" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

在Vue模板中调用辅助函数的正确方法是什么?

感谢任何提示!

1 个答案:

答案 0 :(得分:2)

您可以将其添加到您的组件:

import { addZeroes } from "../../../js/helpers";

export default {
    data() {
        return {
            // populated via AJAX
            restaurants: [
                {
                    categories: []
                }
            ],
        }
    },
    methods: {
        addZeroes // shorthand for addZeroes: addZeroes
    }
}