vue.jsvueuse

Using VueUse composables with the component options api


Is possible to use VueUse with the Options API style? All examples are using Composition one.

I try to use computedAsync. The stock function returns a Promise<VendorItem[]>.

Using Composition API as the example works fine :

const vendors = computedAsync(
    async () => {
        return await stock(db);
    },
    [],
);

But this does not work when I try to use it using the Options API style:

export default defineComponent({
    name: "VendorsList",
    computed: {
        vendors() {
            return computedAsync(
                async () => {
                    return await stock(db);
                },
                [],
            )
        }
    }
})

In the last case, vendors does not contain the array. I try to debug it adding:

    <div v-for="vendor in vendors" class="">
        <pre>{{ JSON.stringify(vendor, null, 4)}}</pre>
        ---------------
    </div>

and the output is something like this

false
---------------
---------------
true
---------------
[
    {
        "id": "00PIL9ljDrgRZrP8MOkl",
        "language": "en"
    },
    {
        "id": "00ZnoY0NXb1ZjQMFQJCC",
        "language": "en"
    },
    {
        "id": "01hO4DKjAprwP8zwUpZU",
        "language": "en"
    }
]
---------------
[
    {
        "id": "00PIL9ljDrgRZrP8MOkl",
        "language": "en"
    },
    {
        "id": "00ZnoY0NXb1ZjQMFQJCC",
        "language": "en"
    },
    {
        "id": "01hO4DKjAprwP8zwUpZU",
        "language": "en"
    }
]
---------------


Solution

  • Simple anwser is no, you can't use vue composables (including VueUse ones) in the option api except for the setup function. Source in the vue documentation.

    The computedAsync composable already creates a computed, so here you are trying to create a computed of a computed. Just move it in the setup function and it will work.

    export default defineComponent({
      name: "VendorsList",
      setup() {
        const vendors = computedAsync(async () => await stock(db), [])
        return { vendors }
      },
    })