首页 > 解决方案 > VueJS 在每个组件上添加生命周期钩子

问题描述

所以我的应用程序中有一个加载器屏幕,想法是在 beforeCreate 钩子上显示加载器屏幕,这样用户就看不到正在渲染的东西,然后在挂载的钩子上删除加载器屏幕。

当你有两个或三个视图/组件时,这很有趣而且很好,但目前我的应用程序有很多,并且将它添加到每个组件/视图对我来说没有多大意义。

所以我想知道,有没有办法在全局范围内向 beforeCreate 和 mount 钩子添加一些东西。像这样的东西:

main.js

Vue.beforeCreate(() => {
    //Show the loader screen
});

Vue.mounted(() => {
    //Hide the loader screen
});

这样它将应用于每个组件和视图

标签: vue.js

解决方案


您可以为此目的使用 mixins,并导入组件。

//mixins.js
export default {
  beforeCreate() {},
  mounted() {}
}

并在组件中添加 mixins:[importedMixins]

您将可以访问“this”。

实际上,您可以使用 vuex 来(mapGetters、mapActions 等)

如果您不想在每个组件中包含 mixins,请尝试使用 vue 插件系统(https://vuejs.org/v2/guide/plugins.html):

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // something logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // something logic ...
  }
}

像这样使用你的插件Vue.use(MyPlugin, { someOption: true })


推荐阅读