The fact that Vue.js 3 already reached the alpha version made me think that… it’s time already for some Vue.js 3 tips!

The idea is to give you some tips related to new features you can find on Vue.js 3 as they get available. For now, we’ll focus on Composition API, one of the most game-changing features!

This first one is specially focused on showing you a basic step-by-step guide or cheatsheet to migrate object-api Vue.js components to use Composition API. In future tips you’ll also see how to apply certain new techniques this API allow us to do as well.

I’ll do that by showing you how to convert an Object-API-based component to use Composition API.

For that, let’s create a MoneyCounter.vue component that basically shows a money amount and allow us to add/substract quantities to it, implemented using the following code:

<template>
  <div>
    <h2>{{ formattedMoney }}</h2>
    <input v-model="delta" type="number">
    <button @click="add">Add</button>
  </div>
</template>

<script>
export default {
  data: () => ({
    money: 10,
    delta: 1
  }),
  computed: {
    formattedMoney() {
      return this.money.toFixed(2);
    }
  },
  mounted() {
    console.log("Clock Object mounted!");
  },
  methods: {
    add() {
      this.money += Number(this.delta);
    }
  },
  watch: {
    money(newVal, oldVal) {
      console.log("Money changed", newVal, oldVal);
    }
  }
};
</script>

#vue #vue.js #api #vue.js 3 #programming

Easily switch to Composition API in Vue.js 3
19.65 GEEK