繁体   English   中英

在 Nuxt 中编写自定义插件

[英]Typescripting custom plugins in Nuxt

在我的 Nuxt 项目中,我创建了一个自定义插件文件,该文件返回 object。 /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`,

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

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

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

根据文档,您需要为 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
  }
}

这个答案也有效,但我发现了一种更简单但更脏的方法来修复它,而无需添加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`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM