It can be beneficial to keep your functions separate from your .vue components for a cleaner code structure. By creating pure components and exporting functions from external files, you allow your .vue components to simply import them. However, this approach is subjective and may not suit every development style.
The example below demonstrates how easy it is to integrate external functions into Vue components (or instances):
const sumFunction = (a, b) => {
return a + b
}
new Vue({
el: "#app",
computed: {
result() {
return sumFunction(Number(this.a), Number(this.b))
}
},
data() {
return {
a: 0,
b: 0
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="number" v-model="a" /><br />
<input type="number" v-model="b" /><br /> a + b = {{result}}
</div>
Your project structure could resemble the following:
externalFunction.js:
export const sumFunction = (a, b) => {
return a + b
}
sumTemplate.vue:
<template>
<div>
<input type="number" v-model="a" /><br />
<input type="number" v-model="b" /><br />
a + b = {{result}}
</div>
</template>
<script>
import { sumFunction } from "@externalFunction"
export default {
computed: {
result() {
return sumFunction(Number(this.a), Number(this.b))
}
},
data() {
return {
a: 0,
b: 0
}
}
}
</script>
It's important to note that in this setup, unit tests play a crucial role. It's essential to monitor the inputs and outputs of your functions to prevent any component failures when making changes.