如何在Vue插件中调用mounted或created?

Ste*_*n-v 5 vue.js vue-component vuejs2

我正在尝试根据这篇文章创建一些插件:

https://alligator.io/vuejs/creating-custom-plugins/

我有一个插件需要在根 Vue 实例挂载或创建时运行一些东西。到目前为止,我只能看到一种将某些东西注入所有组件的方法,这不是我想要的。

我只需要在主 Vue 实例挂载时做一些事情。我怎么能用插件做到这一点?

install插件中的方法似乎不起作用,因为这似乎发生在实际created方法之前。

Dec*_*oon 6

可以有多个根 Vue 组件。“根组件”只是一个使用new语法创建的组件,没有父组件,因此您可以按如下方式检测:

Vue.mixin({
  created() {
    if (!this.$parent) {
      // This is either the root component or a component
      // created with `new` and no parent
    }
  }
})
Run Code Online (Sandbox Code Playgroud)