Use the new composition API in Vue | Tutorial for beginners

Use the new composition API in Vue | Tutorial for beginners

In this article we will be using Vue Composition API inside Vue2.x project setup and build a simple todo app

Composition API is most commonly discussed and new feature syntax of the next major version release of Vue. It’s a completely new approach in making our logic reusable and organize our codebase.

How to get started with the API

We will be using the composition API inside our Vue2.x project with the help of existing plugin, first create our app with Vue CLI

vue create composition-todo

Then we need to install the plugin from our command line:

yarn add @vue/composition-api

We will initialize the plugin into our main.js file with code below:

import Vue from 'vue'
import App from './App.vue'
import CompositionApi from '@vue/composition-api'

Vue.config.productionTip = false
Vue.use(CompositionApi)

new Vue({
  render: h => h(App),
}).$mount('#app')

This is all we need to move ahead working with the API. We will get into using reactive, ref, computed, Vue lifecycle and more. Let’s move on with the code by making our brand new component inside our app.vue file we will import reactive from our API and write the code below

<template>
  <div id="app">
    <section>
      <input type="text" v-model="state.todo" />
      <ul>
        <li v-for="(todo, i) in state.todolist" :key="i">{{todo}}</li>
      </ul>
    </section>
    <button @click="addTodo">Add Todo</button>
  </div>
</template>
<script>
import { reactive, ref } from "@vue/composition-api";
export default {
  setup() {
    const { state, addTodo } = useOurTodo();
    return {
      state,
      addTodo
    };
  }
};
function useOurTodo() {
  let state = reactive({
    todo: "",
    todolist: []
  });
  function addTodo() {
    state.todolist.push(state.todo);
    state.todo = "";
  }
  return {
    state,
    addTodo
  };
}
</script>
<style lang="sass">
</style>

If we look into our code above we can see we have created a setup function and set our reactive data properties and returned its value. With the help of the API we are able to structure our function more readable and reusable way in contrast in the options API before it would have been forced according to structure. We can split our code into little modules.

This is image title

Now we will further group the logic in different section. We will make our changes to make it more well structured.


<template>
  <div id="app">
    <section>
      <h3>My Todo List</h3>
      <input type="text" v-model="state.todo" />
      <ul>
        <li v-for="(todo, i) in state.todolist" :key="i">
          {{todo}}
          <button @click="removeTodo(i)">x</button>
        </li>
      </ul>
    </section>
    <button @click="addTodo">Add Todo</button>
  </div>
</template>

<script>
import { reactive, ref } from "@vue/composition-api";
export default {
  setup() {
    const { state, addTodo, removeTodo } = useOurTodo();
    return {
      state,
      addTodo,
      removeTodo
    };
  }
};

function useOurTodo() {
  let state = reactive({
    todo: "",
    todolist: []
  });

  function addTodo() {
    state.todolist.push(state.todo);
    state.todo = "";
  }
  function removeTodo(i) {
    state.todolist.splice(i);
  }
  return {
    state,
    addTodo,
    removeTodo
  };
}
</script>

<style lang="sass">
</style>

We have made our further changes to the code. This way we can get into more cleaner way in writing our code which can be useful in our code structuring and modularity. Similarly we can use more of the provided composition API features like Props, watchers, context, Lifecycle hooks which will be covered in next article writing.

The code now is improved, but it showcases the importance of logical separation. We don’t have to understand which data or properties or methods belong to which component area, we can simply group it in more readable, reusable, modular functions now.

Happy Coding !

vue vuejs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework. Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

Vue Native is a framework to build cross platform native mobile apps using JavaScript

Vue Native is a framework to build cross platform native mobile apps using JavaScript. It is a wrapper around the APIs of React Native. So, with Vue Native, you can do everything that you can do with React Native. With Vue Native, you get

Creating a Custom Tooltip Component in Vue

There are plenty of libraries out there that will have you up and running with a good tooltip solution in minutes. However, if you are like me, you are sick and tired of giant dependency trees that have the distinct possibility of breaking at any time.

Vue ShortKey plugin for Vue.js

Vue-ShortKey - The ultimate shortcut plugin to improve the UX .Vue-ShortKey - plugin for VueJS 2.x accepts shortcuts globaly and in a single listener.

A Vue component to hzqing vue Timeline

hzqing-vue-timeline . Vue's timeline plugin .A Vue component to hzqing-vue-timeline A Vue time plugin