grupoarrfug.com

Mastering Vue: Transitioning from Options API to Composition API

Written on

Understanding the Migration

This guide provides a comprehensive overview to simplify the transition from the Options API to the Composition API in Vue. Below are examples showcasing the "before" and "after" code snippets.

Key Differences in Script Structure

In your Vue component, you will now employ a single <script> block featuring the setup keyword. The traditional export default with an object is no longer in use; instead, your code should flow linearly.

#### Props Handling

Previously, you defined props as follows:

props: {

icon: String,

name: String

}

In the new structure, you will define props using:

const props = defineProps({

icon: String,

name: String

});

The reference to this is replaced by direct access to props.

#### Emitting Events

In the Options API, you might have had something like:

emits: {

close(accepted: boolean) {

return true;

}

},

Now, you use:

const emit = defineEmits({

close(accepted: boolean) {

return true;

}

});

To emit events, simply call emit('close', saveChanges);.

#### State Management

Instead of using the data function, you will now declare state variables with the ref function:

const showHeaderMenu = ref(false);

To toggle this variable:

showHeaderMenu.value = !showHeaderMenu.value;

Function Definitions

Methods are now defined as arrow functions. For instance, the toggleHeaderMenu function would look like:

const toggleHeaderMenu = () => {

showHeaderMenu.value = !showHeaderMenu.value;

};

Computed Properties

In the new API, computed properties are set up using:

const activeColors = computed(() => {

return colors.filter(color => color.active);

});

Watching Properties

To watch a property, you will use:

watch(() => props.showModal, () => {

internalShowModal.value = true;

});

Lifecycle Hooks

The mounted hook now utilizes:

onMounted(() => {

...

});

Router Usage

For navigation, the router is now accessed via:

const router = useRouter();

router?.push(route);

Summary of Changes

Here's a quick recap of the new syntax for common patterns:

// PROPS

const props = defineProps({

name: String

});

// EMIT

const emit = defineEmits({

close(accepted: boolean) {

return true;

}

});

// DATA

const showHeaderMenu = ref(false);

// METHOD

const toggleHeaderMenu = () => {

...

};

// COMPUTED

const activeColors = computed(() => {

return ...

});

// WATCH

watch(() => props.showModal, () => {

...

});

// ON MOUNTED

onMounted(() => {

...

});

// ROUTER

const router = useRouter();

router?.push(route);

Polyfills for Vue 2.7

For those utilizing Vue 2.7, it's possible to integrate the Composition API. Create a useRouter.ts file with the following code:

import { getCurrentInstance } from 'vue';

export function useRouter() {

return getCurrentInstance()?.proxy.$router;

}

Once you upgrade to Vue 3.0, you can remove this file and utilize the standard Vue hooks.

If you have suggestions for enhancing this guide, feel free to comment below! Additionally, I'm currently designing Vue flashcards, which you can explore on the linked page.

If you found this article helpful and want to see more Vue content, please like, subscribe, and share. Cheers!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Revolutionizing Information Management with RecapioGPT

Discover how RecapioGPT can streamline your summarization process, making information management effortless and efficient.

Understanding Surgery's Impact on Childhood Trauma

Explore how surgical experiences and traumatic events in childhood can affect our energy and emotional well-being.

A Journey to Reconnect: Birthright Africa and Ancestral Roots

Exploring Birthright Africa's mission to connect Black college students with their ancestral roots through free trips.

# The Essential Element in Your Morning Routine for Success

Discover how to transform your mornings into a powerful routine that sets the tone for success and fulfillment throughout your day.

Transform Your Life: 5 Essential Factors for Self-Improvement

Discover five crucial elements for effective self-improvement and how they can lead to a more fulfilling life.

Finding Peace Amidst Distress: Embracing Spiritual Comfort

Exploring how to cope with emotional pain through spiritual guidance and faith.

Embrace Your Inner Light: Discovering Spiritual Change-Makers

Explore the signs of being a Spiritual Change-Maker and how your influence can spark transformation in others.

# OpenAI's ChatGPT Faces New Rivals: A Deep Dive Into the Competition

Explore why OpenAI should be concerned as new chatbots challenge ChatGPT’s dominance, highlighting Claude and Bard’s competitive advantages.