javascript - 如何使自定义装饰器对 vue.js 2 应用程序全局可用?
问题描述
我创建了一个打字稿装饰器,它为传递的方法添加了一些额外的参数。没有使用可选参数的装饰器,它完全可以正常工作。大多数时候不需要传递这些参数,但偶尔需要传递这些参数。
但是我看到其他开发人员不知道要传递的另一个参数是什么,除非他们看到方法的实现或 jsdoc,他们不应该关心这些。
所以我创建了一个装饰器,它将以正确的顺序和正确的状态添加参数。一切正常,但是现在每个人都必须记住向 MyDecorator 添加额外的导入。所以我想让这个装饰器在全球范围内可用。
同样在我们的应用程序中,我们使用装饰器来创建组件、道具、getter、动作。如果我也可以使这些成为全球性的,那就太好了。几乎我们所有的组件都使用这些组件,并且每次导入只是样板文件。(没有错,只是让我们所有人都更容易)
这是应用程序组件语法的示例,其中包含伪代码中的装饰器。
<script lang="ts">
import { Vue, Component, Prop, Emit } from 'vue-property-decorator';
import { MyDecorator } from './src/utils';
import { Getter } from 'vuex-class';
@Component({})
export default class MyComponent extends Vue {
@Getter('something', { namespace: 'whatever' })
something: number;
mounted() {
@MyDecorator()
doSomething('do it please');
}
}
</script>
所有 vue 组件如何在不使用导入的情况下获得可用的装饰器?可能吗?
解决方案
在@LShapz 发表评论后,我看到使用插件可以做到这一点。我仍然需要导入 Vue。
import { Component } from 'vue-property-decorator';
import { MyDecorator } from '@/src/utils';
const MyPlugin: any = {};
MyPlugin.install = (Vue, options) => {
Vue.Awesome = Component; // this I will never use as it will require to edit all files in my project
Vue.MyDecorator = MyDecorator;
Vue.prototype.MyProtoDecorator = MyDecorator;
};
// the MyPlugin can be placed on another file and exported
Vue.use(MyPlugin);
要使用它:
<script lang="ts">
import { Vue } from 'vue-property-decorator';
import { Getter } from 'vuex-class';
@Vue.Awesome({}) // this is to show it is possible. Not practical
export default class MyComponent extends Vue {
@Getter('something', { namespace: 'whatever' })
something: number;
mounted() {
@Vue.MyDecorator() // this is the thing that is practical for my case
doSomething('done it somehow');
@this.MyProtoDecorator() // second way
doSomething('done again');
}
}
</script>
推荐阅读
- java - Dagger2 Maven:com.google.devtools.ksp:symbol-processing-api:jar:1 缺少 POM
- python - 使用 Python 的 Telegram 机器人返回时卡住了
- xslt - 在 xslt 中的特定条件匹配后中断 for 循环
- python - 当代码在 Sypder 单元中运行时,为什么 Python 在同一文件夹中找不到模块
- python - 声音不能通过 cmd 在 python 中播放,但可以通过 idle 工作
- php - 如何根据`Nova Laravel`中的选择字段选项动态填充文本字段
- java - 如何验证小程序是否已安装在 Java 卡上
- r - 如何在列表中的每个数据帧中的不同位置重命名 NA-Column
- angular - 如何防止更改 MatTab 直到确认?
- php - PHP exec() 在 AWS EC2-server 上非常慢