vue.js logo

Vue 3 Composition API


Step 1: Setup the Component

Let's create a simple component that uses the Composition API to manage state and logic. We'll create a component that counts the number of times a button is clicked.


1. Create a new component file: src/components/Counter.vue



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

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

                export default {
                  setup() {
                    // State management
                    const count = ref(0);

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

                    // Return the state and methods to the template
                    return {
                      count,
                      increment
                    };
                  }
                };
                </script>

Explanation

Script:

Import `ref` from Vue: `ref` is used to create a reactive reference to a value.

State Management: `const count = ref(0)` creates a reactive variable `count` initialized to 0.

Methods: The `increment` function updates the `count` value.

Return: The `count` and `increment` function are returned so they can be used in the template.


Step 2: Use the Component

Register and use the `Counter` component in your main `App.vue`:



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

          <script>
          import Counter from './components/Counter.vue';

          export default {
            components: {
              Counter
            }
          };
          </script>

Step 3: Run the Application

Start your Vue application: npm run serve


Now you should see a button in your application that increments a counter each time it's clicked.


Advanced Example: Fetching Data with Composition API

For a more advanced example, let's create a component that fetches data from an API and displays it.


Create a new component file: src/components/DataFetcher.vue



          <template>
            <div>
              <p v-if="loading">Loading...</p>
              <p v-else-if="error">{{ error }}</p>
              <div v-else>
                <h3>{{ data.title }}</h3>
                <p>{{ data.body }}</p>
              </div>
            </div>
          </template>

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

          export default {
            setup() {
              const data = ref(null);
              const loading = ref(true);
              const error = ref(null);

              const fetchData = async () => {
                try {
                  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
                  const result = await response.json();
                  data.value = result;
                } catch (err) {
                  error.value = 'Failed to fetch data';
                } finally {
                  loading.value = false;
                }
              };

              onMounted(fetchData);

              return {
                data,
                loading,
                error
              };
            }
          };
          </script>

Using the DataFetcher Component

Register and use the DataFetcher component in your main App.vue:



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

          <script>
          import DataFetcher from './components/DataFetcher.vue';

          export default {
            components: {
              DataFetcher
            }
          };
          </script>

Conclusion

The Composition API provides a more flexible and reusable way to handle component logic and state in Vue 3. By using functions to encapsulate logic, you can create more modular and maintainable code. The examples provided demonstrate basic and advanced use cases, showing the power and simplicity of the Composition API in Vue 3.