Skip to content
Advertisement

VueJS – call function in external JS file directly from Template

Let’s say that in a VueJS project, I have a HelloWorld.js file like this:

export default {
addNumbers: function (a,b) {
    return a+b;
    }
}

And it’s used from HelloWorld.vue like this:

<template>
  <div>
    <h1>{{addNumbers(1,2)}}</h1>
  </div>
</template>

<script>
import helloWorldJS from './HelloWorld.js'

export default {
  name: 'HelloWorld',
  methods: {
    addNumbers: function(a,b) {
      return helloWorldJS.addNumbers(a,b);
    }
  }
}
</script>

My agony comes from having to ‘duplicate’ the addNumbers function in the methods section of the HelloWorld component.

Is there a simple way to make the external addNumbers function available from the template section?

Advertisement

Answer

you could export as const you function like:

export const addNumbers = (a,b) => a+b;

then at your vue file you could write as:

import { addNumbers }  from './HelloWorld.js'

export default {
  name: 'HelloWorld',
  methods: {
    addNumbers // this is equal to addNumbers: addNumbers
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement