0
votes

I'm js newbie, I want to use external functions in vue component data bindings but it fails to work

helper.js

function groupArrayOfObjects(list, key) {  
    return blah blah
}

function parseDate(d) {      
    return bla bla
}

export { groupArrayOfObjects, parseDate };

vue component:

Vue warn]: Property or method "parseDate" 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.

 <template>
          <div>{{parseDate(date) }}</div>  
    </template>

    import { groupArrayOfObjects, parseDate } from "@/assets/js/helper.js";
    export default {
        methods:{
          abc(){ groupArrayOfObjects(param1, param2);}
        }
    }
2

2 Answers

1
votes

Try to spread the helper functions inside the methods option :

import * as helpers from "@/assets/js/helper.js";

export default {
  methods: {
    abc() { groupArrayOfObjects(param1, param2); },
    ...helpers
   
  }
}

in template :

 <template>
          <div>{{parseDate(date) }}</div>  
 </template>
1
votes

You can't use imported functions in your template, as they are not really part of the component. If you want to use those imported functions you need to add them to your components method object. Similar to what you already did with your groupArrayOfObjects function.

import { groupArrayOfObjects, parseDate } from "@/assets/js/helper.js";

export default {
  methods: {
    abc() { groupArrayOfObjects(param1, param2); },
    
    // either wrap your function
    foo(date) { parseDate(date) },
    
    // or just add it directly
    parseDate,
  }
}