Search code examples
vuejs2vue-cli-4

VueJS plugins conflict


I created two plugins in my VueJS app powered by Vue CLI 4 but when I tried to use it in my page only one will be working

| plugins
|-- axios.vue
|-- authentication.vue

axios.vue

import Vue from "vue";

Plugin.install = function(Vue) {
  Vue.prototype.$myName = "Dean Armada";
};

Vue.use(Plugin);

export default Plugin;

authentication.vue

import Vue from "vue";

Plugin.install = function(Vue) {
  Vue.prototype.$name = "Chris Guinto";
};

Vue.use(Plugin);

export default Plugin;

main.js

import axios from "./plugins/axios.js";
import authentication from "./plugins/authentication.js";

Vue.use(axios);
Vue.use(authentication);

instructions.vue

<template>
  <div>
      Hello World
  </div>
</template>

<script>
  export default {
    created() {
      console.log(this.$name);
      console.log(this.$myName);
    }
  }
</script>

<style lang="scss" scoped>

</style>

TAKE NOTE

  • The output above will be "Dean Armada" only and the console.log(this.$name) is undefined
  • But if I commented out the Vue.use(axios) the console.log(this.$name) will work so the output will be "Chris Guinto" and the other one is undefined because the axios plugin is not activated

So how can I make them both work at the same time?


Solution

  • Perhaps try and simplify it a little with the following approach?

    // plugins/axios.js
    export default {
        install(Vue){   
            Vue.prototype.$myname = "Dean Armada";
        }
    }
    
    // plugins/authentication.js
    export default {
        install(Vue){   
            Vue.prototype.$name = "Chris Guinto";
        }
    }
    
    // main.js
    import axios from "./plugins/axios.js";
    import authentication from "./plugins/authentication.js";
    
    Vue.use(axios);
    Vue.use(authentication);
    
    new Vue({
      el: '#app',
      render: h => h(App)
    })