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

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

集成@tencentcloud/chat

bash 复制代码
npm i @tencentcloud/chat

创建Chat插件

ts 复制代码
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

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组件

ts 复制代码
<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>

SDK文档地址

相关推荐
不像程序员的程序媛29 分钟前
Nginx日志切分
服务器·前端·nginx
北原_春希38 分钟前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS38 分钟前
echarts天气折线图
javascript·vue.js·echarts
尽意啊40 分钟前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜40 分钟前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive41 分钟前
Vue3使用ECharts
前端·javascript·echarts
竹秋…41 分钟前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.41 分钟前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts
shmily麻瓜小菜鸡42 分钟前
前端文字转语音
前端
人良爱编程1 小时前
Hugo的Stack主题配置记录03-背景虚化-导航栏-Apache ECharts创建地图
前端·javascript·apache·echarts·css3·html5