Lakmal Premaratne
Lakmal Premaratne

Reputation: 1229

Using js helper function from parent and child component

I have a parent component (say, CustomerOrder) and a child component (say OrderLine). In CustomerOrder.vue, I will be including multiple OrderLine by iterating over an array. I have a helper js function that I need to use in both CustomerOrder and OrderLine. I can import this js file in CustomerOrder and call the js function. But I cannot import the js file in OrderLine because it gives an error (vue.runtime.esm.js?2b0e:1888 TypeError: _vm.formatNumber is not a function) when the function is being called. My requirement is to use the helper js function from parent and multiple children of the same type.

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>

vue.runtime.esm.js?2b0e:1888 TypeError: _vm.formatNumber is not a function is raised when formatNumber in OrderLine is called. Is it because

FYI:

utils.js:

import Numbro from 'numbro'

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

Upvotes: 0

Views: 135

Answers (1)

Emīls Gulbis
Emīls Gulbis

Reputation: 2070

You should add (define) formatNumber in methods like

methods: {
  formatNumber
}

otherwise you can't use it in template

Also you can check https://v2.vuejs.org/v2/guide/filters.html and add formatNumber to filters instead of methods. Then use in template like {{ 2300 | formatNumber }}

Upvotes: 2

Related Questions