使用父级和子级组件的js帮助器功能

时间:2019-07-08 17:07:43

标签: vue.js vue-component

我有一个父组件(例如CustomerOrder)和一个子组件(例如OrderLine)。在CustomerOrder.vue中,我将通过遍历数组来包含多个OrderLine。我有一个CustomerOrderOrderLine都需要使用的辅助js函数。我可以在CustomerOrder中导入此js文件并调用js函数。但是我无法在OrderLine中导入js文件,因为在调用函数时会给出错误(vue.runtime.esm.js?2b0e:1888 TypeError: _vm.formatNumber is not a function)。我的要求是使用父代和同类型的多个子代的辅助js函数。

CustomerOrder.vue

<template>
    <span class="caption">{{ formatNumber(1500) }} LKR</span>
    <v-layout wrap>
      <order-line v-for="line in orderLines" :key="line.id" :general_data="line"></order-line>
    </v-layout>
</template>

<script>
    import { formatNumber } from '../utils'
</script>

OrderLine.vue

<template>
    <span class="caption">{{ formatNumber(2300) }} LKR</span>
</template>

<script>
    import { formatNumber } from '../utils'
</script>
调用OrderLine中的vue.runtime.esm.js?2b0e:1888 TypeError: _vm.formatNumber is not a function时引发

formatNumber。是因为

仅供参考:

utils.js

import Numbro from 'numbro'

export function formatNumber (value, numberOfDecimals) {
  return Numbro(value).format({
    thousandSeparated: true,
    trimMantissa: true,
    mantissa: numberOfDecimals
  })
}

1 个答案:

答案 0 :(得分:2)

您应在formatNumber中添加(定义)methods,如

methods: {
  formatNumber
}

否则您不能在模板中使用它

您还可以检查https://vuejs.org/v2/guide/filters.html并将formatNumber添加到filters而不是methods。然后在模板中使用 {{ 2300 | formatNumber }}