[英]Vue JS - custom properties on vue component gives TS errors
I have created some Vue middleware and I am trying to add a custom property to one of my components in Vue like so:我已经创建了一些 Vue 中间件,我正在尝试向 Vue 中的一个组件添加自定义属性,如下所示:
middleware.js:中间件.js:
import { VueConstructor } from 'vue/types';
function eventPlugin(vue: VueConstructor): void {
const Socket = new someClass();
Object.defineProperties(vue.prototype, {
$socket: {
get: function get() {
return Socket;
},
},
});
vue.$socket = Socket;
}
myComponent.js我的组件.js
const MyComponent = Vue.extend({
name: 'MyComponent',
$socket: {
event(data: any) {
}
},
methods: {
MyMethod() {
}
}
})
app.js应用程序.js
import Vue from 'vue';
import eventPlugin from './middleware.js';
import MyComponent from './myComponent.js'
Vue.use(eventPlugin);
export default new Vue({
render: (h) => h(MyComponent),
}).$mount('#app');
The custom property I am trying to add here is obviously socket
.我在这里尝试添加的自定义属性显然是
socket
。 The problem is when I add it I get typescript errors:问题是当我添加它时,我得到 typescript 错误:
Object literal may only specify known properties, and 'socket' does not exist in type 'ComponentOptions<Vue, DefaultData, DefaultMethods, DefaultComputed, PropsDefinition<Record<string, any>>, Record<...>>'.
Object 字面量只能指定已知属性,并且 'socket' 不存在于类型 'ComponentOptions<Vue, DefaultData, DefaultMethods, DefaultComputed, PropsDefinition<Record<string, any>>, Record<...>>' 中。
As you can see in middleware.js
I have tried defining the property there so I am not sure why I am receiving the error?正如您在
middleware.js
中看到的那样,我尝试在那里定义属性,所以我不确定为什么会收到错误消息?
When adding instance properties or component options, you also need to augment the existing type declarations .添加实例属性或组件选项时,您还需要扩充现有的类型声明。
Based on Augmenting Types for Use with Plugins (Vue 2) :基于与插件一起使用的增强类型(Vue 2) :
To type-hint the $socket
instance property:要键入提示
$socket
实例属性:
declare module 'vue/types/vue' { interface VueConstructor { $socket: string } } export {}
To type-hint the $socket
component option:要键入提示
$socket
组件选项:
import Vue from 'vue' declare module 'vue/types/options' { interface ComponentOptions<V extends Vue> { $socket?: string } } export {}
The type declarations above should go in a .d.ts
file in your src
directory.上面的类型声明应该 go 在您的
src
目录中的.d.ts
文件中。 If using VS Code, any new .d.ts
files might require restarting VS Code to load.如果使用 VS Code,任何新的
.d.ts
文件可能需要重新启动 VS Code 才能加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.