Reputation: 7801
I wrote a plugin:
var MyCoolVuePlugin = {
install(Vue) {
Vue.prototype.doStuff = function() {
console.log("I'm a useless plugin")
}
}
}
export default MyCoolVuePlugin;
In my main.js
, where my frontend starts and the Vue instance is created, I included my plugin:
import Vue from 'vue';
import App from './App';
import MyCoolVuePlugin from './plugin';
Vue.use(MyCoolVuePlugin);
window.vApp = new Vue({
el: '#app',
router: Router,
components: { App },
template: '<App/>'
});
And then in my App.vue
, I have some stuff like this:
<template>
<div id="app">
<h1>Is Anybody There</h1>
<some-other-component />
</div>
</template>
<script>
import SomeOtherComponent from "./components/SomeOtherComponent";
export default {
name: "App",
components: {
"some-other-component": SomeOtherComponent
},
data() {
...
},
mounted() {
// How do I access my Vue plugin
// I can do:
vApp.doStuff();
// Or I can do:
this.$parent.doStuff();
}
};
</script>
<style lang="scss">
...
</style>
How do I access my Vue plugin as shown in the mounted
function of App.vue? When I ask "how do I" I mean what is the correct, recommended way? Perhaps I'm failing at searching but so far I've been unable to find documentation related to accomplishing this.
Upvotes: 0
Views: 1561
Reputation: 31352
When your plugin is installed using Vue.use()
it calls the install method of the plugin in which you are adding a method to the prototype
of Vue
This allows you to access this method in any component using this.doStuff()
So you can access it in a mounted hook as
mounted() {
this.doStuff();
}
I recommend that you name the property or method you are attaching on the prototype with a $
prefix.
So Vue.prototype.$doStuff
can be accessed in any component as this.$doStuff
. This is just a convention.
Upvotes: 2