I have a Vue app that is built on the Webpack. The component has a couple of simple computed propertys like getting sum amount from inputs. But now I need to make it possible to replace the summation function from an external file not related to the current assembly, as well as the ability to add buttons (and) other functions from this file to the current template - subtraction, multiplication, division depending on the flags (hide / show) set from the external file. What is the best way to approach it? Any thoughts?
Thanks
1 Answer 1
I don't think that it's a bad idea to have your functions outside your .vue components. That way it's much easier to create pure components, and just export those functions from those files - your .vue components can import them. (But I think it's an opinionated pattern you either use or don't use.)
The snippet below only shows that it's simple to add external functions to Vue components (or instance in this case):
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>
So, your files could look something like this:
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>
The only thing that should be emphasized: with this setup unit tests have an even more important role. You have to watch for inputs and outputs of your functions, so when you change them no components would break.
windowobject?window.myCrazyFunction = () => { // code }