【发布时间】:2022-01-03 18:15:57
【问题描述】:
我创建了一个插件并想在我的一个组件中使用它。
位于~/plugins/socket.client.ts下的插件代码:
import { io } from 'socket.io-client'
import { Plugin } from '@nuxt/types'
const socketIOPlugin: Plugin = (_, inject) => {
const socketUrl: string | undefined = process.env.socket_url
if (!socketUrl || socketUrl.length <= 0) {
throw new Error('socketUrl is undefined.')
}
const socket = io(socketUrl)
inject('socket', socket)
}
export default socketIOPlugin
在 nuxt.config.js 中注册。
plugins: ['~/plugins/socket.client']
我在我的组件中这样使用它:
import Vue from 'vue'
export default Vue.extend({
mounted() {
this.$socket.on("example:hello", (data: any) => {
console.log(data);
});
},
})
但是,当我启动 nuxt 时,我收到以下错误:
Property '$socket' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.
我已经尝试添加一个 vue-shim.d.ts 文件,但仍然没有任何变化。
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
declare module "vue/types/vue" {
import { Socket } from "socket.io-client";
interface Vue {
$socket: Socket;
}
}
我似乎找不到解决这个问题的方法。谁能帮帮我?
【问题讨论】:
标签: typescript vue.js nuxt.js