VueJS 添加到每个组件的生命周期钩子中



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

当您有两个或三个视图/组件时,这很有趣,但目前我的应用程序远不止于此,将其添加到每个组件/视图对我来说没有多大意义。

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

主.js

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

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

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

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

并在组件中添加混合:[导入混合]

您将可以访问"此"。

实际上你可以使用和vuex(mapGetters,mapActions等(

如果你不想在每个组件中包含 mixins,请尝试使用 vue 插件系统 (https://v2.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 })

在 vue-router 中,您的请求有一些非常棘手的东西。我从来没有使用过之后每个,但之前每个都完美地工作。

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

这是一个文档

还有一个名为"beforeRouteEnter"的钩子。

链接到之前路线输入文档

最新更新