问题:如何使自定义装饰器对 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>
Logo

前往低代码交流专区

更多推荐