{{announcement.body}}
{{announcement.title}}

Building Applications With The Vue 3 Composition API

DZone 's Guide to

Building Applications With The Vue 3 Composition API

In this article, we discuss how to build applications with Vue's new Composition API as an alternative to the current Options API.

· Web Dev Zone ·
Free Resource

With the imminent release of Vue 3, this is a great time to build an app with the new Vue 3 Composition API. While this change in how you can build components is one of Vue 3’s biggest features, here are some other key benefits of this version:

  • Smaller and faster.
  • Improved TypeScript support.    
  • Exposes lower-level APIs.   
  • Apps will be more maintainable. 
Let’s get back to the Composition API by building a simple TODO application. Look at the blocks below for a high-level difference between a component written with the Composition API, and the older Options API. We’ll dive into additional details as we build the application.

Options API with Vue 2

JavaScript




xxxxxxxxxx
1


 
1
let app = new Vue({
2
  data:{ /* Application data */ },
3
  computed:{ /* computed properties */ },
4
  methods:{ /* functions and methods */ },
5
})



Composition API with Vue 3

JavaScript




xxxxxxxxxx
1


 
1
let app = new Vue({
2
  beforeCreate(){},
3
  setup(){},
4
  created(){}
5
})



Getting Started: Configuring the Development Environment

For this tutorial, we will be using the Eclipse IDE with the CodeMix plugin installed, though the concepts presented can be followed in any IDE:

  • Download Eclipse IDE and install CodeMix from the Eclipse marketplace or via Genuitec.com.
  • Alternatively, for a standalone installer, use Angular IDE — yes, it has full support for Vue too!
  • If the Vue pack isn’t already installed, install it using the CodeMix Extension Browser (Help > CodeMix Extensions).
You may also like: Build a Secure App With Spring Boot and Vue.js.

If you’re looking for an IDE to take on development with frameworks like Angular, React, and Vue.js, or languages like Python and Rust, CodeMix has you covered. For Vue, install the Vue pack or the famed Vetur extension for Vue support. Codemix is compatible with all Eclipse-based IDEs and tools, such as MyEclipse, Spring Tools Suite, and JBoss Tools.
 


Creating a Vue Project Using CodeMix

We can now create our application using the CodeMix Project Wizard. To create a new Vue Project, navigate to File > New > Project > CodeMix > Vue Project. Ensure you choose the, “A Vue CLI-built application” option in the wizard before clicking Finish.

creating a new Vue project

The Vue CLI creates a Vue 2 application. By adding the composition-api module to the project, we can use the Composition API in our Vue 2 application (this will not make it a Vue 3 application). Please run the following command in Terminal:

npm install @vue/composition-api

Then, modify your main.js file as shown below:

JavaScript




xxxxxxxxxx
1


 
1
import Vue from 'vue'
2
import App from './App.vue'
3
import VueCompositionApi from '@vue/composition-api';
4
 
          
5
Vue.use(VueCompositionApi);
6
Vue.config.productionTip = false
7
new Vue({
8
  render: h => h(App),
9
}).$mount('#app')



It’s a good idea to use Bootstrap to add some styling and icons to our application. For that, we need to add the following lines of code to our main HTML file in the <head> section:

HTML




xxxxxxxxxx
1


 
1
<link rel="stylesheet" href="https://bootswatch.com/4/lux/bootstrap.min.css">
2
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">



So, go ahead and open up the index.html file in the src folder and update it, as shown below: 

Java




x
14


 
1
<!DOCTYPE html>
2
<html lang="en">
3
  <head>
4
    <meta charset="utf-8">
5
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
6
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
7
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
8
    <title>Composition-Todo</title>
9
    <link rel="stylesheet" href="https://bootswatch.com/4/lux/bootstrap.min.css">
10
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
11
  </head>
12
  <body>
13
    <noscript>
14
      <strong>We



Now we've come to the main feature — using the composition API to build our application. The key benefit of this API is enhanced maintainability of your code by keeping logical concerns grouped together instead of being split up across component options like data, props, methods, etc.

While the benefits are not immediately apparent in our simple TODO application, imagine a more complex application, where the logic for different capabilities would normally be split across the file —the more your application grows in complexity, the harder it becomes to read and maintain.

As a comparison, we’ve shown how this component would be implemented with both the Options API and the Composition API. Please copy the composition version into the <script> section of your app.vue file.

Options API

HTML




xxxxxxxxxx
1
21


1
<script>
2
export default {
3
  data(){
4
    return {
5
      todo: "",
6
      todos: []
7
    };
8
  },
9
  methods:{
10
    addTodo(){
11
      if (this.todo!='') {
12
        this.todos.push(this.todo);
13
        this.todo ='';
14
      }
15
    },
16
    removeTodo(i){
17
      this.todos.splice(i,1)
18
      },
19
  }
20
}
21
</script>



Composition API

JavaScript




xxxxxxxxxx
1
32


1
import { reactive } from "@vue/composition-api";
2
export default {
3
  setup(){
4
    const {state, addNewTodo, removeTodo} = useTodo();
5
    return {
6
      state,
7
      addNewTodo,
8
      removeTodo
9
    };
10
  }
11
}
12
function useTodo(){
13
  let state = reactive({
14
    todo: "",
15
    todos: []
16
  });
17
  function addNewTodo(){
18
    state.todos.push(state.todo);
19
    state.todo = '';
20
  }
21
  function removeTodo(i){
22
    if (state.todo!='') {
23
       state.todos.push(state.todo);
24
       state.todo ='';
25
    }
26
  }
27
  return{
28
    state,
29
    addNewTodo,
30
    removeTodo
31
  };
32
}



The Composition API manages reactivity differently than the Options API. There are two ways to deal with state and reactivity in the new Composition API, Refs and Reactive. With Reactive, we tell Vue about which properties of an object should be watched and therefore rendered when needed. Ref, instead, gives a value property to any object, and whenever we assign a new value to it, Vue will update the template with the new value.      

At the crux of the Composition API is the setup function, which is just a function that returns properties and functions to the template. It is important to mention that any data that uses refs or reactive, needs to be returned as objects from the setup function.

setting up our project


We now move on to styling; insert the following CSS into the <style> section of the Vue file: 

CSS




xxxxxxxxxx
1
18


1
#app {
2
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
3
  -webkit-font-smoothing: antialiased;
4
  -moz-osx-font-smoothing: grayscale;
5
  text-align: center;
6
  color: #2c3e50;
7
  margin-top: 60px;
8
}
9
 
          
10
.fa {
11
  color:red;
12
  margin-left: 20px;
13
  /* height: 40px; */
14
}
15
.fa:hover{
16
  color: black;
17
  /* height: 50px; */
18
}



 Then, add the following code in the template section: 

HTML




xxxxxxxxxx
1
27


 
1
<template>
2
  <div id="app">
3
 <section class = "container">
4
   <div class="card">
5
     <div class="card-header"> <h3> Add New Todo</h3></div>
6
 
          
7
   <div class="card-body">
8
      <input type="text" class = "form-control" v-model ="state.todo"/>
9
      <button class="btn btn-primary my-2" @click="addNewTodo"> Add Todo</button>
10
   </div>
11
   </div>
12
 
          
13
  <div class="container my-5">
14
  <div class="card">
15
    <div class="card-header"> <h3> MyTodos</h3></div>
16
    <div class="card-body">
17
     <ul class="list-group">
18
       <li class="list-group-item" v-for="(todo, i) in state.todos" :key="i">
19
        {{todo}} <i class="fa fa-trash" aria-hidden="true" @click="removeTodo(i)"></i>
20
       </li>
21
     </ul>
22
    </div>
23
  </div>
24
  </div>
25
 </section>
26
  </div>
27
</template>



When pressing the green play button located on the top right of our editor, CodeMix automatically launches the server and opens the Live Preview Pane. In it, we can observe our application running without the need of an external browser, as shown on the gif below:

adding a ToDo item

In Closing

While the Composition API is a much better way of working with components, it is important to note that this API is an alternative to the current Options API and not a replacement. We can still work with components using options, mixins, and scoped slots, as is the norm in Vue 2. The Vue core team has stated that the Options API would still continue to be supported in Vue 3.

You can download the source code for this app from our GitHub repository.



Further Reading

Topics:
web dev ,vue ,spa ,frontend ,angular ,react ,tutorial ,options api ,composition api

Published at DZone with permission of George Anderson , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}