2

Our team is converting an app from Vue 2 to 3 and I am working on the final steps. I am investigating whether we can convert our mixin files to composables. I have yet to find any documentation to support whether you can use composables with optionsAPI. I have tried a little sample but I am seeing the limitations:

COMPOSABLE file useComposables:

import { ref, computed } from 'vue'

export default () => {
    let first = ref('First')
    let last = ref('Last')
    let mycomputed = computed(() => {
        return `${first.value} *** ${last.value}`
    })

    return {
        first, mycomputed
    }
}

COMPONENT:

import useComposables from '@/utils/useComposable'

created () {
        let { first, mycomputed } = useComposables()
        console.log('first', first.value)
        console.log('mycomputed', mycomputed.value)
    },

<template>
    mycomputed {{ mycomputed }}
</template>

So, I see when I try to do interpolation on mycomputed computed variable in the template, the component doesn't have access to the computed variable because it is not in the computed option and doesn't belong to 'this'.

I can't seem to find any documentation to support using composables with options API. Am I missing something or is this a no-go?

Thanks

8
  • YOu can use the setup function instead of the created, and return your computed in there to access it from the template. I recommend you switch to composition API for many benefits Commented Nov 23, 2022 at 1:49
  • @Duannx title explicitly says "Using composables with OptionsAPI". Commented Nov 23, 2022 at 1:50
  • @kissu I just provide a better option Commented Nov 23, 2022 at 1:52
  • 1
    @Duannx the current question is still quite interesting and deserves some attention. I'm curious myself tbh. Just giving an irrelevant answer will not help OP. It's like asking: "what is your age?" and getting "I really love strawberries, they are better than an age" as an answer. Commented Nov 23, 2022 at 2:13
  • 3
    Hey break it up guys!. I did get it working by doing this: ``` setup() { let { first, mycomputed } = useComposables() return { first, mycomputed } }, ``` Thanks Commented Nov 23, 2022 at 14:08

1 Answer 1

1

OP achieved to solve that by using the following:

setup() {
    let { first, mycomputed } = useComposables()

    return {
        first, mycomputed
    }
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.