vuejs / composition-api

Composition API plugin for Vue 2
https://composition-api.vuejs.org/
MIT License
4.19k stars 342 forks source link

Unable to use reactive outside of setup #872

Closed shadskii closed 2 years ago

shadskii commented 2 years ago

Calling reactive outside of a component's setup function or composable results in the following error message:

Uncaught Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.

see replit

Example Code ```vue ```

Expected behavior

reactive should not throw an error and should behave as Vue.observable when used outside of setup or a composable and return a reactive object.

Creating reactive object stores outside of components in Vue 3 using reactive is a legitimate pattern (see) and supporting it in the @vue/composition-api will help ease the upgrade to Vue 3.

If this is not possible to implement, this limitation should be documented in the readme.

posva commented 2 years ago

The error is pretty self explanatory: you are not calling Vue.use(VueCompositionAPI) before calling reactive(). You have to ensure it's called in the right order. E.g:

// a.js
export default reactive({})
// plugins
Vue.use(VueCompositionAPI)
// main.js
import state from './a.js'
import './plugins' // too late!

Instead, do

// main.js
import './plugins'
import state from './a.js'

Remember to use the forum or the Discord chat to ask questions!

shadskii commented 2 years ago

@posva thanks for the solution. Importing my plugins as a side effect before my main component did the trick. A very frustrating and nuanced error. Hopefully this issue can serve to help anyone with a similar problem in the future.

Thanks for the help!