Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Getting Started with Vue 3 Composition API

Tech 2

1. Project Initialization

  • Install Vue CLI 3: npm install -g @vue/cli
  • Create a new project: vue create my-project
  • Enstall the Composition API in the project: npm install @vue/composition-api --save
  • Set up the Composition API in main.js using Vue.use():
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);

2. The setup Function

The setup function executes after beforeCreate and before created.

It accepts two parameters: setup(props, context) {}

  • props: Parameters passed from external sources.
  • context: A context object similar to this in Vue 2, providing access to properties like context.attrs, context.emit, and context.refs. Note that this cannot be used inside setup.

Advantages of setup:

Instead of declaring multiple options such as data(), methods, created, mounted, and watch, you can now consolidate all logic within the setup function. This approach enhances modularity by grouping related state and methods together, reducing redundancy when creating new components.

3. ref and reactive

  • ref: The ref() function creates a reactive data object from a given value, e.g., const counter = ref(0). Access the value via counter.value.
  • reactive: Creates a reactive data object, similar to the object returned by data() in Vue 2, e.g., const state = reactive({ counter: 0 }). Access values via state.counter.

Why have two ways to create reactivity? Vue's team designed these APIs to accommodate different coding styles. For example, ref is akin to direct variable declarations (e.g., let x = 1), while reactive is like storing values in an object (e.g., let state = { x: 1 }).

Important: When using the spread operator (...) on a reactive object, the result loses reactiivty. Use ...toRefs(state) to convert it to ref objects.

4. isRef and toRefs

  • isRef(): Checks if a value is a ref object.
  • toRefs(): Converts a reactive object into ref objects. This is useful when returning multiple reactive objects from setup:
setup() {
    const state = reactive({
        counter: 0
    });
    const myRef = ref(1);

    return {
        ...toRefs(state),
        myRef
    };
}

Why use toRefs? A reactive object must be returned as state directly, not as { state }. This function facilitates returning multiple reactive objects. For simplicity, using ref directly is often recommended.

5. computed and watch

In Vue 3, computed and watch are declared within the setup function.

  • computed:
setup() {
    const counter = ref(1);
    const incrementedCounter = computed(() => counter.value + 1);
    return {
        counter,
        incrementedCounter
    };
}
  • watch:
const counter = ref(1);
watch(() => console.log(counter.value));

6. Lifecycle Hooks

  • beforeCreate → use setup()
  • created → use setup()
  • beforeMountonBeforeMount
  • mountedonMounted
  • beforeUpdateonBeforeUpdate
  • updatedonUpdated
  • beforeDestroyonBeforeUnmount
  • destroyedonUnmounted
  • errorCapturedonErrorCaptured

Two new debugging hooks are added:

  • onRenderTracked
  • onRenderTriggered

Example:

export default {
    onRenderTriggered(event) {
        debugger;
        // Inspect which dependency triggers re-rendering
    }
};

7. provide and inject

provide() and inject() enable data passing between nested components, usable only within setup(). Use provide() in a parent component to pass data down, and inject() in child components to receive it.

Parenet component:

setup() {
    const counter = ref(1);
    provide('counter', counter); // Pass counter to child
},

Child component:

setup() {
    const counter = inject('counter'); // Receive counter
},

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.