【问题标题】:Typescripting custom plugins in Nuxt在 Nuxt 中编写自定义插件
【发布时间】:2020-01-28 02:47:27
【问题描述】:

在我的 Nuxt 项目中,我创建了一个返回对象的自定义插件文件。 /helpers/settings:

export const settings = {
  baseURL: 'https://my-site.com',
  ...
};

我在/plugins/settings.ts注册这个文件:

import Vue from 'vue';
import { settings } from '~/helpers/settings';

Vue.prototype.$settings = settings;

nuxt.config.js:

export default {
  ...
  plugins: [
    '~/plugins/settings',

然后,在一个组件中,我可以像这样使用我的插件:

export default Vue.extend({
  data() {
    return {
      url: `${this.$settings.baseURL}/some-path`,

一切都按预期工作,除了在我的控制台中,我从我在组件中引用我的插件的行中收到一个打字错误:

Property '$settings' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.

因此我的问题是:将类型应用于我的自定义插件的正确方法是什么,这样我每次使用它时都不会收到此错误?

【问题讨论】:

    标签: javascript typescript vue.js plugins nuxt.js


    【解决方案1】:

    根据docs,您需要为 Vue 扩充类型文件。

    将以下代码放入名为plugin-types.d.ts的文件中。

    // 1. Make sure to import 'vue' before declaring augmented types
    import Vue from 'vue'
    
    // 2. Specify a file with the types you want to augment
    //    Vue has the constructor type in types/vue.d.ts
    declare module 'vue/types/vue' {
      // 3. Declare augmentation for Vue
      interface Vue {
        $settings: string
      }
    }
    

    【讨论】:

      【解决方案2】:

      这个answer 也可以,但我发现了一种更简单但更脏的方法来修复它,而无需添加plugin-types.d.ts 文件。

      只需为您的组件添加一个带有插件名称的属性,如下所示:

      @Component
      export default class YourComponent extends Vue {
        private $settings!: string; // your plugin here
        private url: string = `${this.$settings.baseURL}/some-path`
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多