How to create a reusable component or code in Vue

February 25, 2022

Tags: Technologies
vue
Unsplash

 

Vue.js is one of the preferred frameworks for frontend developers. As per the definition given on its official website, Vue is a progressive style framework designed to create user interfaces. One of the main things that set it apart from other monolithic frameworks is that it was designed to be adopted incrementally.

 

Vue's Single-Files Component structure is responsible for separating the components into: HTML Markup, Behavior and Styles. One of our expert Vue developers explained how this structure is different from the one used by other similar frameworks like Angular and React.

 

“It differs from Angular, for example, because a component exists within a single file and its parts are not segregated across multiple files. And templates differ from React in that they are declaratively written in a format that is a superset of HTML (i.e. all HTML is also a valid Vue template) and not necessarily with JSX (although it is possible to use JSX and other template engines as well) ".

 

Create reusable components in Vue

 

We will learn to build a reusable component in Vue, which will be used to reuse it in Create or Edit or anywhere that requires the same code and functionality. Reusing a component or code helps us avoid writing the same code and functionality multiple times.

 

First, create the UserComponent.vue component in the components directory and add the following code:

 

<template>
  <div class="max-w-lg mx-5 text-left">
    <form @submit.prevent="$emit('submit-form', form)">
      <div class="mb-6">
        <label for="name" class="text-sm font-medium text-gray-900 block mb-2"
          >Name</label
        >
        <input
          type="text"
          id="name"
          class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
          placeholder="Name"
          v-model="form.name"
          required=""
        />
      </div>
      <div class="mb-6">
        <label for="email" class="text-sm font-medium text-gray-900 block mb-2"
          >Your email</label
        >
        <input
          type="email"
          id="email"
          class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
          placeholder="Email"
          v-model="form.email"
          required=""
        />
      </div>
      <div class="mb-6">
        <label
          for="address"
          class="text-sm font-medium text-gray-900 block mb-2"
          >Address</label
        >
        <input
          type="text"
          id="address"
          class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
          placeholder="Address"
          v-model="form.address"
          required=""
        />
      </div>
      <div class="mb-6">
        <label for="text" class="text-sm font-medium text-gray-900 block mb-2"
          >Mobile no</label
        >
        <input
          type="text"
          id="mobile_no"
          class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
          placeholder="Mobile no"
          v-model="form.mobile"
          required=""
        />
      </div>

      <button
        type="submit"
        class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center"
      >
        Submit
      </button>
    </form>
  </div>
</template>

<script>
export default {
  name: "UserComponent",
  props: {
    user: Object,
  },
  data() {
    return {
      form: {
        name: this.user ? this.user.name : "",
        address: this.user ? this.user.address : "",
        email: this.user ? this.user.email : "",
        mobile: this.user ? this.user.mobile : "",
      },
    };
  },
};
</script>

 

Next, we are going to create the CreateUser.vue component. After creating it, import the UserComponent and add it to the template as shown in the following code:

 

<template>
  <div class="px-5">
    <!-- success msg component -->
    <Success :msg="msg" v-show="success" />
    <UserComponent @submit-form="saveUser" />
  </div>
</template>

<script>
import UserComponent from "./UserComponent";
import Success from "./Success";

export default {
  name: "CreateUser",
  components: {
    UserComponent,
    Success,
  },
  data() {
    return {
      success:false,
      msg: "",
    };
  },
  methods: {
    saveUser() {
      this.success = true;
      this.msg = "User added";
      console.log("User info saved");
    },
  },
};
</script>

 

Same for the EditUser component, adding the following code:

 

<template>
  <div class="px-5">
    <!-- success msg component -->
    <Success :msg="msg" v-show="success" />
    <!-- edit user which has user data as prop -->
    <UserComponent :user="user" @submit-form="updateUser" />
  </div>
</template>

<script>
import UserComponent from "./UserComponent";
import Success from "./Success";

export default {
  name: "EditUser",
  components: {
    UserComponent,
    Success,
  },
  props: {
    user: Object,
  },
  data() {
    return {
      success:false,
      msg: "",
    };
  },
  methods: {
    updateUser() {
      this.success = true;
      this.msg = "User Updated";
      console.log("User info updated");
    },
  },
};
</script>

 

The next thing would be to create the Success component, with the purpose of displaying the success message after editing the user. To create it in the components directory, add:

 

<template>
  <div
    class="w-full mx-4 text-green-300 p-2 mx-auto mb-6 bg-green-600 border border-green-700 rounded"
  >
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: "Success",
  props: {
    msg: {
      type:String,
    },
  },
};
</script>

 

Almost at the last step. Add the CreateUser and EditUser components to the App.vue file:

 

<template>
  <div id="app">
    <h4>Save information of User</h4>
    <CreateUser />
    <br />
    <h4>Update User Information</h4>
    <EditUser :user="user" />
  </div>
</template>

<script>
import CreateUser from "./components/CreateUser";
import EditUser from "./components/EditUser";

export default {
  name: "App",
  components: {
    CreateUser,
    EditUser,
  },
  data() {
    return {
      user: {
        name: "Alex",
        address: "info building",
        email: "alex@xyz.com",
        mobile: "1122334456",
      },
    };
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: anti-aliased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  colour: #2c3e50;
  margin-top: 60px;
}
</style>

 

And in this way we have successfully reused the component or code in a Vue application.

 

Our expert Rootstack developers have used this technique to solve the technical problems presented by our clients at an international level. If you want to be part of this team, just click here and take the first step to a bright future.

 

We recommend you on video


 

Yes, I liked thiscontent.