vue.js - VueJS 在每个组件上添加生命周期钩子
问题描述
所以我的应用程序中有一个加载器屏幕,想法是在 beforeCreate 钩子上显示加载器屏幕,这样用户就看不到正在渲染的东西,然后在挂载的钩子上删除加载器屏幕。
当你有两个或三个视图/组件时,这很有趣而且很好,但目前我的应用程序有很多,并且将它添加到每个组件/视图对我来说没有多大意义。
所以我想知道,有没有办法在全局范围内向 beforeCreate 和 mount 钩子添加一些东西。像这样的东西:
main.js
Vue.beforeCreate(() => {
//Show the loader screen
});
Vue.mounted(() => {
//Hide the loader screen
});
这样它将应用于每个组件和视图
解决方案
您可以为此目的使用 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 })
推荐阅读
- docker - 使用 hyperledger-fabric v1.0.0 使 docker 出错
- javascript - Express 在 PUT 请求中无法识别来自 Postman 的正确请求正文
- python - 使用 Selenium 和 Scrapy 通过 onclick 抓取显示的数据
- php - 如何创建一个在 php 中自动填写表单的唯一链接?
- c# - C# - 如何在 DataTable 中进行数学运算
- r - 使用 purrr 或 rlist 从 json 文件中查找元素
- css - CSS 不寻常的使用 :after
- javascript - 使用 Typescript 和 Vue 时如何从 .js 文件中导入函数
- reactjs - 在循环中从另一个函数反应调用函数
- python - python matplotlib pyplot show 安装 vnc 后失败?