What is the purpose of Vue.use() while importing a plugin? If we have already used vue.use , is it required to add it to the components

Viewed 6911

I'm using the plugin vue-flag-icon - https://www.npmjs.com/package/vue-flag-icon for flags, In their documentation I saw the following steps for initialising.

import FlagIcon from 'vue-flag-icon'
Vue.use(FlagIcon);

Do I need to have this? This is not specified in their docs!

export default {
    components: {
        FlagIcon. /// do i need to give it here ?
    },
}

What is the purpose of this Vue.use(...), It's working fine even if I remove that. Can somebody help me out?

Checked the vue documentation - https://v2.vuejs.org/v2/guide/plugins.html.

Did not get a clear idea about it

1 Answers

Vue.use automatically prevents you from using the same plugin more than once, so calling it multiple times on the same plugin will install the plugin only once.

For the flag component, it declares a global component that you can refer within your components, such that in the following example will render correctly.

in vue-flag-icon source code

install: function (Vue) {
    if (VuePlugin.installed) {
        return;
    }
    VuePlugin.installed = true;
    Vue.component('flag', Flag);
}

You can see that with Vue.component('flag', Flag) that this is a root level component declaration, therefore, in your components, you do not require to declare something like following


Unnecessary if using Vue.use

import { Flag } from "vue-flag-icon"

export default {
  components: { Flag }
}

If Vue.use is not used, the flag tag in the template will throw an error if you do not include it as a component within your vue init.

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <flag iso="it" />
    <flag iso="gb" />
    <flag iso="us" />
  </div>
</template>

<script>

export default {
  name: 'app',
}
</script> 
Related