How to use the vue 3 composition api

Step 1: Create a new Vue 3 project

To get started, make sure you have Vue CLI installed. Open your terminal and run the following command:

npm install -g @vue/cli

Once Vue CLI is installed, create a new Vue 3 project using the following command:

vue create my-project

Follow the prompts and select the default preset (or choose manually based on your preferences).

Step 2: Set up a component with the Composition API

Navigate to the project directory:

cd my-project

Open the project in your preferred code editor.

Inside the src directory, create a new file called HelloWorld.vue and add the following code:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

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

export default {
  name: 'HelloWorld',
  setup() {
    const count = ref(0);

    const increment = () => {
      count.value++;
    };

    return {
      count,
      increment,
    };
  },
};
</script>

Step 3: Render the component

Open the src/App.vue file and replace its content with the following code:

<template>
  <div id="app">
    <HelloWorld />
  </div>
</template>

<script>
import HelloWorld from './HelloWorld.vue';

export default {
  name: 'App',
  components: {
    HelloWorld,
  },
};
</script>

Step 4: Run the application

Save your changes and go back to the terminal.

Run the following command to start the development server:

npm run serve

Visit http://localhost:8080 in your browser, and you should see the “Count” text and a button. Clicking the button will increment the count.

Congratulations! You’ve successfully created a Vue 3 application using the Composition API. This API allows you to organize your component logic into reusable functions and makes it easier to manage state and side effects.

Feel free to expand on this example and explore more features of the Composition API as you build your Vue 3 applications. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *