I am trying to create some plugins according to this article:
https://alligator.io/vuejs/creating-custom-plugins/
I have a plugin that needs to run something when the root Vue instance mounts or is created. So far I can only see a way to inject something into all components which is not what I would want.
I simply need to do something when the main Vue instance mounts. How can I do this with a plugin?
The install
method from the plugin does not seem to do the trick because this seems to happen before the actual created
method.
And among both of them, mounted hooks are also known as most used hooks because it is easily handled when there is no concept involved of “Server-side Rendering ” and created is more useful when we are dealing with servers and fetching data from backend API. It occurs at the earliest stage of the Vue lifecycle.
Register one or more global components or custom directives with app.component() and app.directive() . Make a resource injectable throughout the app by calling app.provide() . Add some global instance properties or methods by attaching them to app.config.globalProperties .
The `mounted()` Hook in VueVue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render. For example, the below Vue component uses the mounted() hook to make an HTTP request to the JSONPlaceholder API.
It's possible to have multiple root Vue components. A "root component" is just a component created with the new
syntax and no parent component, so you can detect this as follows:
Vue.mixin({
created() {
if (!this.$parent) {
// This is either the root component or a component
// created with `new` and no parent
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With