[英]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.