Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call mounted or created within a Vue plugin?

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.

like image 958
Stephan-v Avatar asked Dec 04 '17 12:12

Stephan-v


People also ask

What is the difference between mounted and created in Vue?

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.

How do I use VueJS plugins?

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 .

How does mounted work in Vue?

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.


1 Answers

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
    }
  }
})
like image 144
Decade Moon Avatar answered Nov 15 '22 06:11

Decade Moon