ame*_*ght 2 javascript plugins typescript vue.js nuxt.js
在我的 Nuxt 项目中,我创建了一个返回对象的自定义插件文件。/helpers/settings:
export const settings = {
baseURL: 'https://my-site.com',
...
};
Run Code Online (Sandbox Code Playgroud)
我将此文件注册在/plugins/settings.ts:
import Vue from 'vue';
import { settings } from '~/helpers/settings';
Vue.prototype.$settings = settings;
Run Code Online (Sandbox Code Playgroud)
并在nuxt.config.js:
export default {
...
plugins: [
'~/plugins/settings',
Run Code Online (Sandbox Code Playgroud)
然后,在组件中,我可以像这样使用我的插件:
export default Vue.extend({
data() {
return {
url: `${this.$settings.baseURL}/some-path`,
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作,除了在我的控制台中,我从组件中引用插件的行中收到打字稿错误:
Property '$settings' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.
Run Code Online (Sandbox Code Playgroud)
因此我的问题是:将类型应用于自定义插件的正确方法是什么,这样我每次使用它时都不会出现此错误?
根据文档,您需要增加 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6247 次 |
| 最近记录: |