Skip to content

Raigyo/progressor-compo-api

Repository files navigation

Vue 3 composition API: Progressor

September 2021

🔨 CRUD using Vue3 and the new composition API. From Udemy Vue 3 par la pratique - Samir Medjdoub / Code Concept.


Demo on Netlify.

Composition API vs Options API

One of the big features that the Vue 3 release brings is the Composition API. In Vue 2, components were built using the Options API. The CodeSandbox below shows a very simple component using the Options API.

Component with Options API

In Vue 3, in addition to the Options API, you now have the option to use the Composition API. Below is an example of the exact same component, but using the Composition API instead.

<template>
  <div id="app">
    <p>You clicked {{ numOfClicks }} times.</p>
    <button @click="handleClick()">Click me to increment!</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      numOfClicks: 0,
    };
  },
  created() {},
  methods: {
    handleClick: function () {
      this.numOfClicks++;
    },
  },
};
</script>

<style>
#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;
}
</style>

Component with Composition API

<template>
  <div id="app">
    <p>You clicked {{ numOfClicks }} times.</p>
    <button @click="handleClick()">Click me to increment!</button>
  </div>
</template>

<script>
import { ref } from "vue";

export default {
  name: "App",
  setup() {
    let numOfClicks = ref(0);

    function handleClick() {
      numOfClicks.value++;
    }

    return {
      handleClick,
      numOfClicks,
    };
  },
};
</script>

<style>
#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;
}
</style>

You'll notice the big difference here is the setup function. This is a new component option that holds all of the logic for the component. Instead of defining data, methods, and lifecycle hooks as separate component options, all of these now lie in the setup function.

Another important difference is that you no longer have to use this to access your data in methods.

Source

Useful links

About

Vue 3 and composition API. (Demo on Netlify)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published