user1729972
user1729972

Reputation: 896

Vue.use vs Vue.component on root Vue component

Vue.use makes functionality global whilst calling Vue.component in the root Vue component (typically app.vue) has the same effect. I've seen a sample app using both (many Vue.component and Vue.use calls within the root js). Have been googling but don't see anything explaining this pattern.

What is the (subtle) difference?

Upvotes: 10

Views: 6606

Answers (1)

skirtle
skirtle

Reputation: 29132

For starters see:

https://v2.vuejs.org/v2/api/#Vue-component
https://v2.vuejs.org/v2/api/#Vue-use

It's a bit vague to say 'making functionality global'. There's a need to pin down a bit more clearly exactly what that means in each case.

Vue.component is used to register a component globally. That makes it available within templates by the specified name. So Vue.component('rainbow', componentDefinition) will allow you to use <rainbow> within all your templates without having to explicitly import it into those components. For more information about the different ways to register components see:

https://v2.vuejs.org/v2/guide/components-registration.html

Vue.use is used to invoke a plugin. Effectively a plugin is just a JavaScript function and it can do whatever it wants. That function might register components (using Vue.component) but many plugins do other things, such as registering directives or adding global mixins.

It may well be that in the sample app you're studying the plugins are all registering components, which gives the impression that Vue.use is much the same as Vue.component. If so, that's just a coincidence. I suggest that you take a look at the source code for some of the plugins to get a better idea of what they're doing and how they work.

Both Vue.component and Vue.use will typically be used in the main entry point file for your application. Likely that'll be called something like main.js. They might not be called directly, for example a plugin might call Vue.component, but the global nature of their outcomes usually makes it necessary to make all such calls prior to kicking off the application itself with new Vue.

If you've got Vue.component or Vue.use calls inside a .vue file then that suggests you're doing something wrong, even if it's app.vue. A .vue file should just export a component, it shouldn't have any global side-effects such as registering components.

Upvotes: 10

Related Questions