vue3集成腾讯IM(无UI)教程

825 阅读1分钟

前言:由于一些项目需要集成IM,但是不需要UI,网上的教程比较少,所以分享一下我是如何集成的,希望各位一起讨论最佳方案。

集成@tencentcloud/chat

npm i @tencentcloud/chat

创建Chat插件

import MonoChat from './index.vue'
import TencentCloudChat from "@tencentcloud/chat";
import type { ChatSDK } from '@tencentcloud/chat'
import type { App, InjectionKey, Plugin } from "vue";
export const chatKey = Symbol() as InjectionKey<ChatSDK>
interface Options {
    appId: number,
    logLevel?: number
}
export const createChat = (options: Options): Plugin => {
    return {
        install: (app: App) => {
            if (!options.appId) {
                throw new Error('chat-plugin: 请传appId')
            }
            const chat = TencentCloudChat.create({
                SDKAppID: options.appId
            })
            chat.setLogLevel(options.logLevel || 0);
            app.provide(chatKey, chat)
        }
    }
}

export default MonoChat

集成到main.ts

import { createApp } from 'vue'
import App from './App.vue'
import { createChat } from './components/MonoChat'
const chat = createChat({
    appId: import.meta.env.VITE_IM_SDK_APP_ID,
    logLevel: import.meta.env.VITE_IM_SDK_APP_LOG_LEVEL
})
createApp(App).use(chat).mount('#app')

创建ChatUI组件

<script setup lang="ts">
import { inject, onMounted, onUnmounted } from "vue";
import { chatKey } from "./index";
import TencentCloudChat from "@tencentcloud/chat";

defineOptions({
  name: "ChatUI",
});
const userId = "";
const userSig = "";
const chat = inject(chatKey);
const onMessageReceived = (event: any) => {
  console.log(event);
};

onMounted(() => {
  chat?.login({ userID: userId, userSig });
  chat?.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
});
onUnmounted(() => {
  chat?.destroy();
  chat?.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
});
</script>
<template>
  <div>ChatUI</div>
</template>
<style lang="less" scoped></style>

image.png

SDK文档地址