2

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?

2 Answers 2

7

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

Comments

0

You can't directly import the method and use it on the template in vue. You can only use functions that are defined in the methods object section. But if you want to make it global you can use plugins like below.

import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

new Vue({
   render: (h) => h(App)
}).$mount("#app");

const MyPlugin = {
   install(Vue, options) {
      Vue.prototype.addNumbers = (a, b) => {
        return a + b;
      };
   }
};
Vue.use(MyPlugin);

Then you can directly call the function in the template

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

<script>
export default {
   name: 'HelloWorld',
   methods: {
   }
}
</script>

Comments

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.