在我的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>>>'.
因此,我的问题:将类型应用于自定义插件的正确方法是什么,以便每次使用时都不会收到此错误?
根据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
}
}