【问题标题】:How to use in imported function in template?如何在模板中的导入函数中使用?
【发布时间】:2017-11-12 18:30:03
【问题描述】:

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

<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 模板中调用辅助函数的正确方法是什么?

感谢任何提示!

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

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

    import { addZeroes } from "../../../js/helpers";
    
    export default {
        data() {
            return {
                // populated via AJAX
                restaurants: [
                    {
                        categories: []
                    }
                ],
            }
        },
        methods: {
            addZeroes // shorthand for addZeroes: addZeroes
        }
    }
    

    【讨论】:

    • 你是对的,这就是我最初的方式,但由于它是一种在多个组件中使用的方法,我认为提取它是一个好主意。
    • 模板通过调用 this.property 隐式访问方法和属性。您必须将导入的函数复制到需要它的每个组件,或者在 mixins 上查找文档。使用 mixin,您可以将函数添加到每个组件中,但要注意名称冲突。
    • 嗨,我的意思是将导入的实用程序函数分配给组件方法中具有相同名称的方法,或者,您可以按照 akatakritos 的建议查看 mixins
    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多