Build a Crud application using Vue Composition API.

Build a Crud application using Vue Composition API


The composition API is a new and optional way of creating and organizing components in a Vue 3 application.

The Composition API allows reactive component logic to be defined more intuitively by allowing all the code for a specific feature (search, for example), to be grouped together. Using the Vue composition API will make your application more scalable and reusable between several components.

In this article, we will build a simple Crud application using the composition API. let’s start by creating a simple vue js application.

Before we get started here’s a word from our sponsor.

Xtreme Vuesax Admin is easy to use and powerful VueJs admin dashboard template based on Vue CLI, Vuex & Vuesax component framework.

It comes easy to use features and it is highly customizable. You can create nice looking applications or products using our Free Vuesax admin template.

Creating A Vuejs Application

We will use the Vue CLI to build a simple application. To do that open up your terminal and type the following:

cd desktop
mkdir composistiontest && cd composistiontest
vue create vuecompositionapi

What we are doing basically is creating a new directory in our desktop and the we use the Vue create command to create a new Vuejs application.Running this command will prompt some questions to setup the application.Choose the default preset to setup the new application.

After installation, move into the folder using the cd vuecompositionapi and run npm run serve.you could open up the application in any of the text editors of your choice.

Now that we have our application up and running, lets build a simple CRUD application to see how our composition API works.

We will start by setting up our user interface for the application.Lets modifying our component/HelloWorld.vue component to this:

<template>
  <section>
    <div class="form-container">
      <h2>Add User</h2>
      <form>
        <div>
          <label>Name</label>
          <br />
          <input type="text" />
        </div>
        <div>
          <button type="submit" class="submit">Add User</button>
        </div>
      </form>
    </div>
    <div class="list-container">
      <ul>
        <li>
          Wisdom Ekpot
          <span style="float:right;padding-right:10px;">
            <button>X</button>
          </span>
        </li>
      </ul>
    </div>
  </section>
</template>
<script>
export default {};
</script>
<style scoped>
input {
  width: 20%;
  height: 30px;
  border: 2px solid green;
}
.submit {
  margin: 10px;
  padding: 10px;
  border-radius: 0px;
  border: 0px;
  background: green;
  color: white;
}
ul li {
  list-style: none;
  border: 2px solid green;
  width: 30%;
  margin-top: 10px;
}
</style>

And we will have this result:

Now that we have our user interface, we need to install the Vue Composition API to install our application. To do that run :

npm install --save @vue/composition-api

Then, to actually import it onto your project — we’ll have to include it in the main.js file. To do this, just add the following lines:

import VueCompositionApi from '@vue/composition-api' 
Vue.use(VueCompositionApi)

Now that we have registered the Vue Composition API globally in our application, we can now use it in all our application components.

We need to bring it into our HelloWorld component by importing it in the component:


import { reactive } from "@vue/composition-api";

And the add some event listeners to the application.lets do that by modifying our template to this:


<template>
  <section>
    <div class="form-container">
      <h2>Add User</h2>
      <form @submit.prevent="addUser">
        <div>
          <label>Name</label>
          <br />
          <input v-model="state.input" type="text" />
        </div>
        <div>
          <button type="submit" class="submit">Add User</button>
        </div>
      </form>
    </div>
    <div class="list-container">
      <ul v-for="(user,index) in state.users" :key="index">
        <li>
          {{user}}
          <span style="float:right;padding-right:10px;">
            <button @click="removeUser(index)">X</button>
          </span>
        </li>
      </ul>
    </div>
  </section>
</template>

In Vue 3 use the data and methods option to define state and add functions rather we have access to a setup method.This method is called after the lifecycle hook beforeCreate and prior to create.

We will declare the state variable and methods inside this setup method by doing this:


setup() {
    const { state, addUser, removeUser } = userList();
    return { state, addUser, removeUser };
  }

After declaring this, we need to define our component state by doing this:


function userList() {
  let state = reactive({
   input: "",
   users: ["Wisdom"]
  });
  return { state };
}

The state here is scoped to the userList function.We define our input state that we will bind to our input field and also define our users array that will hold all our users.After defining this, always remember to return the states and methods.

Now that we have defined our state, we need to define all the methods that we declared in our setup function.

Lets define our addUser function:


let addUser = () => {
    state.users.push(state.input);
    state.input = "";
  };
  return { state, addUser };

The add functionality will take the data in the input field and push it into the users array using the push method.Always remember to return the state or method.

Lets implement deleting a user.We will get the index of the user and then remove the user from the users array using the splice method:


let removeUser = i => {
    state.users.splice(i, 1);
  };
return { state, addUser, removeUser };

It’s important that everything we want to be able to access from the template is returned by both the userList and setup() methods.

Conclusion

The Composition API is a great way to make your code more readable and maintainable. People actually get confused when using this keyword which was a standard in Version 2 of Vuejs. With the composition API introduced in Vuejs 3, handling of methods and component state is made easier. For source code click here.


Share on social media

//