We've all been here. Good code avoids repetition. If you repeat the same code in more than one file, how about making it a component? Use your own threshold/judgement to measure if the code really needs to be a component.
How do I do this?
I'll take you through how to create a Global(component that can be used app-wide) button component in NuxtJs but can also apply for Vue.js.
First create the component file in your components directory, in my case PrimaryButton.vue
. The code inside my PrimaryButton component looks something like this
<template>
<button class="rounded-button-cyan subheading4" @click="callback($event)">
{{ buttonText }}
</button>
</template>
<script>
export default {
props: {
buttonText: String,
},
methods: {
callback: function (e) {
this.$emit("click", e);
},
},
};
</script>
In the above snippet we have created a global PrimarButton that can take in a prop buttonText
and a click event as well.
So let's now use it. We can now use the button in any file like...
<template>
<PrimaryButton @click="showAlert()" buttonText="Show Alert" />
</template>
<script>
export default {
methods: {
showAlert() {
alert("EARTH HACKED 💪💪💪💪");
},
},
};
</script>