Skip to content

Vue Composition API: Properties and Functions

Mike Lyttle edited this page May 11, 2023 · 2 revisions

Class Component

    count = 0;
    increment(): void {
        this.count++;
    }

Composition API

import { ref } from "vue";
const count = ref(0);
function increment(): void {
    count.value++;
}

Notes

  • Since properties and functions are no longer accessed with the this. prefix, be sure to verify that no function parameters share the same names, as a conflict can lead to cryptic bugs.

  • ref() returns an object that wraps the desired type, allowing access through the value property.

  • The parameter passed to ref() is the initial value and is how the type is inferred.

  • Complex types can be specified via a generic argument.

    const count = ref<number | undefined>(undefined);

    If you supply a generic argument but omit the initial value, it infers the type as a union that includes undefined.

    const count = ref<number>();

    (This is equivalent to the previous example.)

Documentation

Clone this wiki locally