0

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);}
        }
    }

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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,
  }
}

Comments

0

You can import the parseDate function from helper and expose this function for the template.

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

<script>
import { parseDate } as helpers from "@/assets/js/helper.js";

export default {
  methods: {
    parseDate
  }
}
</script>

1 Comment

While this might be a valid solution you should include some explanation about why it works and how it solves the problem. Don't forget to quote and link to any relevant documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.