facebook

Building Applications With The Vue 3 Composition API

George Anderson
Frontend and backend development guru, lover of all things computer... and cats! Hopes to make your coder life a breeze by sharing some tips and tricks of the trade.
Posted on Dec 19th 2019
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.
let app = new Vue({
  data:{ /* Application data */ },
  computed:{ /* computed properties */ },
  methods:{ /* functions and methods */ },
})
Options API with Vue 2
let app = new Vue({
  beforeCreate(){},
  setup(){},
  created(){}
})
Composition API with Vue 3

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)

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.
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 below:
import Vue from 'vue'
import App from './App.vue'
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
}).$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:

<link rel="stylesheet" href="https://bootswatch.com/4/lux/bootstrap.min.css">
<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 below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>Composition-Todo</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/lux/bootstrap.min.css">  
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  </head>
  <body>
    <noscript>
      <strong>We're sorry but Composition-Todo doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>
Now we 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 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
<script>
export default {
  data(){
    return {    
      todo: "",
      todos: []
    };
  },
  methods:{
    addTodo(){
      if (this.todo!='') {
        this.todos.push(this.todo);
        this.todo ='';
      }
    },
    removeTodo(i){
      this.todos.splice(i,1)
      },
  }
}
</script>
Composition API
import { reactive } from "@vue/composition-api";
export default {
  setup(){
    const {state, addNewTodo, removeTodo} = useTodo();
    return {
      state,
      addNewTodo,
      removeTodo
    };
  }
}
function useTodo(){
  let state = reactive({
    todo: "",
    todos: []
  });
  function addNewTodo(){
    state.todos.push(state.todo);
    state.todo = '';
  }
  function removeTodo(i){
    if (state.todo!='') {       
       state.todos.push(state.todo);
       state.todo ='';
    }
  }
  return{
    state,
    addNewTodo,
    removeTodo
  };
}

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 an object which properties 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.


Vue Intellisense in Codemix

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

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.fa {
  color:red;
  margin-left: 20px;
  /* height: 40px; */
}
.fa:hover{
  color: black;
  /* height: 50px; */
}

Then, add the following code in the template section:

<template>
  <div id="app">
 <section class = "container">
   <div class="card">
     <div class="card-header"> <h3> Add New Todo</h3></div>

   <div class="card-body">
      <input type="text" class = "form-control" v-model ="state.todo"/>
      <button class="btn btn-primary my-2" @click="addNewTodo"> Add Todo</button>
   </div>
   </div> 

  <div class="container my-5">
  <div class="card">
    <div class="card-header"> <h3> MyTodos</h3></div>
    <div class="card-body">
     <ul class="list-group">
       <li class="list-group-item" v-for="(todo, i) in state.todos" :key="i">
        {{todo}} <i class="fa fa-trash" aria-hidden="true" @click="removeTodo(i)"></i>
       </li>
     </ul>
    </div>
  </div>
  </div>
 </section>
  </div>
</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: Live Preview in CodeMix

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. To learn more about the Composition API, we recommend  this course at Vue Mastery.

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

If you’re not already on the latest CodeMix, download it now to take advantage of all it has to offer! Have any questions or suggestions about this article or any of our products? Let us know your thoughts via Twitter or through the CodeMix forums. Happy Coding!