1

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?

1 Answer 1

2

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

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.