【问题标题】:VueJS Adding to lifecycle hooks on every componentVueJS 在每个组件上添加生命周期钩子
【发布时间】:2019-01-18 00:04:21
【问题描述】:

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

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

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

main.js

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

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

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

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您可以为此目的使用 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 })

    【讨论】:

    • 这是朝着正确方向迈出的一步,但理想情况下,我希望避免向每个组件和视图添加相同的内容..
    • @AdamSilva 所以,也许是插件?并像这样添加 mixins: Vue.mixin({ created: function () { // 一些逻辑 ... } ... }) vuejs.org/v2/guide/plugins.html
    • 是的,这是一个很好的解决方法。我希望有一个更直接的方法来解决这个问题。
    【解决方案2】:

    vue-router 中的请求与您的请求非常相似。我从未使用过 afterEach 但 beforeEach 效果很好。

    router.beforeEach((to, from, next) => {
      /* must call `next` */
    })
    
    router.beforeResolve((to, from, next) => {
      /* must call `next` */
    })
    
    router.afterEach((to, from) => {})
    

    Here is a documentation

    还有一个叫做'beforeRouteEnter'的钩子。

    Link to beforeRouteEnter docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-04
      • 2017-09-29
      • 1970-01-01
      • 2017-10-11
      • 2020-01-14
      • 2020-03-15
      • 2016-07-18
      • 1970-01-01
      相关资源
      最近更新 更多